From 008e54c1dd407b6edd680fccf78cd194365e0507 Mon Sep 17 00:00:00 2001 From: Martin Oberhuber Date: Sat, 5 Nov 2016 09:25:59 +0100 Subject: Fix #923 - support CMAKE_CROSSCOMPILING_EMULATOR for tests Replaced legacy syntax of cmake add_test() with more modern syntax. This allows running gtests's own tests on remote (cross) systems using CMAKE_CROSSCOMPILING_EMULATOR with cmake-3.3 or newer. --- googletest/cmake/internal_utils.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/cmake/internal_utils.cmake b/googletest/cmake/internal_utils.cmake index 8878dc1..93b9e51 100644 --- a/googletest/cmake/internal_utils.cmake +++ b/googletest/cmake/internal_utils.cmake @@ -216,7 +216,7 @@ find_package(PythonInterp) # from the given source files with the given compiler flags. function(cxx_test_with_flags name cxx_flags libs) cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN}) - add_test(${name} ${name}) + add_test(NAME ${name} COMMAND ${name}) endfunction() # cxx_test(name libs srcs...) -- cgit v0.12 From c958e26fd02d43a916ff297c89eee22166fe7be7 Mon Sep 17 00:00:00 2001 From: Scott Slack-Smith Date: Fri, 30 Jun 2017 17:12:56 +0100 Subject: *Silence false positive memory leaks reported by Microsoft's debug CRT* MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a new RAII MemoryIsNotDeallocated class that excludes memory allocations from Microsoft’s debug CRT leak detection report. We use this RAII class to silence 2 false positive leaks that are caused by memory allocations that are intentionally never deallocated. *Background* The MS debug CRT has a lightweight memory leak detection mechanism that can only detect if a memory allocation is missing a matching deallocation. Consequently, it will report a false positive leak for memory that’s intentionally never deallocated. For example, memory that’s reachable for the entire lifetime of a app. Note the MS debug CRT is always tracking memory allocations but the final memory leak report is disabled by default. As you can’t avoid paying for its cost, you may as well use it. The memory leak report can be enabled by calling the following function #ifdef _MSC_VER _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); #endif // _MSC_VER anywhere before exiting main. For example, the following are the false positive leaks reported before this change; Detected memory leaks! Dumping objects -> {750} normal block at 0x015DF938, 8 bytes long. Data: < ] > 00 F9 5D 01 00 00 00 00 {749} normal block at 0x015DEE60, 32 bytes long. Data: <` ] ` ] ` ] > 60 EE 5D 01 60 EE 5D 01 60 EE 5D 01 01 01 CD CD {748} normal block at 0x015DF900, 12 bytes long. Data: <8 ] ` ] > 38 F9 5D 01 60 EE 5D 01 00 00 00 00 {747} normal block at 0x015DA0F8, 24 bytes long. Data: < > FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 Object dump complete. As you can see from above it’s not easy to identify the above are false positives. Consequently, if false positive leaks are not fixed or silenced, then it becomes impractical to identify real memory leaks. --- googletest/src/gtest-port.cc | 52 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index d80bd80..edd115d 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -279,6 +279,43 @@ void Mutex::AssertHeld() { << "The current thread is not holding the mutex @" << this; } +namespace { + +// Use the RAII idiom to flag mem allocs that are intentionally never +// deallocated. The motivation is to silence the false positive mem leaks +// that are reported by the debug version of MS's CRT which can only detect +// if an alloc is missing a matching deallocation. +// Example: +// MemoryIsNotDeallocated memory_is_not_deallocated; +// critical_section_ = new CRITICAL_SECTION; +// +class MemoryIsNotDeallocated +{ +public: + MemoryIsNotDeallocated() : old_crtdbg_flag_(0) { +#ifdef _MSC_VER + old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); + // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT + // doesn't report mem leak if there's no matching deallocation. + _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF); +#endif // _MSC_VER + } + + ~MemoryIsNotDeallocated() { +#ifdef _MSC_VER + // Restore the original _CRTDBG_ALLOC_MEM_DF flag + _CrtSetDbgFlag(old_crtdbg_flag_); +#endif // _MSC_VER + } + +private: + int old_crtdbg_flag_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated); +}; + +} // namespace + // Initializes owner_thread_id_ and critical_section_ in static mutexes. void Mutex::ThreadSafeLazyInit() { // Dynamic mutexes are initialized in the constructor. @@ -289,7 +326,11 @@ void Mutex::ThreadSafeLazyInit() { // If critical_section_init_phase_ was 0 before the exchange, we // are the first to test it and need to perform the initialization. owner_thread_id_ = 0; - critical_section_ = new CRITICAL_SECTION; + { + // Use RAII to flag that following mem alloc is never deallocated. + MemoryIsNotDeallocated memory_is_not_deallocated; + critical_section_ = new CRITICAL_SECTION; + } ::InitializeCriticalSection(critical_section_); // Updates the critical_section_init_phase_ to 2 to signal // initialization complete. @@ -528,10 +569,17 @@ class ThreadLocalRegistryImpl { return 0; } + // Return a newly constructed ThreadIdToThreadLocals that's intentionally never deleted + static ThreadIdToThreadLocals* NewThreadIdToThreadLocals() { + // Use RAII to flag that following mem alloc is never deallocated. + MemoryIsNotDeallocated memory_is_not_deallocated; + return new ThreadIdToThreadLocals; + } + // Returns map of thread local instances. static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() { mutex_.AssertHeld(); - static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals; + static ThreadIdToThreadLocals* map = NewThreadIdToThreadLocals(); return map; } -- cgit v0.12 From b22e8dec408935a7f76420026a738eeb61f8af38 Mon Sep 17 00:00:00 2001 From: Henry Fredrick Schreiner Date: Thu, 5 Apr 2018 13:38:33 +0200 Subject: Clean up cache non-advanced variable for subproject --- googlemock/CMakeLists.txt | 18 ++++++++++++++---- googletest/CMakeLists.txt | 25 ++++++++++++++++++++----- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/googlemock/CMakeLists.txt b/googlemock/CMakeLists.txt index bac2e3b..7d66eb2 100644 --- a/googlemock/CMakeLists.txt +++ b/googlemock/CMakeLists.txt @@ -5,10 +5,6 @@ # ctest. You can select which tests to run using 'ctest -R regex'. # For more options, run 'ctest --help'. -# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to -# make it prominent in the GUI. -option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) - option(gmock_build_tests "Build all of Google Mock's own tests." OFF) # A directory to find Google Test sources. @@ -55,6 +51,20 @@ endif() # if they are the same (the default). add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/gtest") + +# These commands only run if this is the main project +if(CMAKE_PROJECT_NAME STREQUAL "gmock" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution") + + # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to + # make it prominent in the GUI. + option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) + +else() + + mark_as_advanced(gmock_build_tests) + +endif() + # Although Google Test's CMakeLists.txt calls this function, the # changes there don't affect the current scope. Therefore we have to # call it again here. diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index b09c46e..2a9b989 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -5,10 +5,6 @@ # ctest. You can select which tests to run using 'ctest -R regex'. # For more options, run 'ctest --help'. -# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to -# make it prominent in the GUI. -option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) - # When other libraries are using a shared version of runtime libraries, # Google Test also has to use one. option( @@ -60,6 +56,25 @@ if (COMMAND set_up_hermetic_build) set_up_hermetic_build() endif() +# These commands only run if this is the main project +if(CMAKE_PROJECT_NAME STREQUAL "gtest" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution") + + # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to + # make it prominent in the GUI. + option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) + +else() + + mark_as_advanced( + gtest_force_shared_crt + gtest_build_tests + gtest_build_samples + gtest_disable_pthreads + gtest_hide_internal_symbols) + +endif() + + if (gtest_hide_internal_symbols) set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN 1) @@ -86,7 +101,7 @@ include_directories( if (MSVC AND MSVC_VERSION EQUAL 1700) add_definitions(/D _VARIADIC_MAX=10) endif() - + ######################################################################## # # Defines the gtest & gtest_main libraries. User tests should link -- cgit v0.12 From dfddc987186100c98d93a830d6ca88fa66ab3dbc Mon Sep 17 00:00:00 2001 From: tisi1988 Date: Wed, 27 Jun 2018 22:47:18 +0200 Subject: FIX: Compilation warning with GCC regarding a non-initialised member from MutexBase class. --- googletest/include/gtest/internal/gtest-port.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 437a4ed..08c5049 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -2093,7 +2093,7 @@ class MutexBase { // This allows initialization to work whether pthread_t is a scalar or struct. // The flag -Wmissing-field-initializers must not be specified for this to work. # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ - ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false } + ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false, 0 } // The Mutex class can only be used for mutexes created at runtime. It // shares its API with MutexBase otherwise. -- cgit v0.12 From 4bcc9b9807b256e2a59daabb86156f8658031b68 Mon Sep 17 00:00:00 2001 From: Masaru Tsuchiyama Date: Wed, 23 May 2018 21:11:45 +0900 Subject: This closes #1595: fix compiler error with Visual Studio 2017 on Win10 JP. non-ASCII charactors are interpreted as Shift-JIS on the environment. But the charators in the files are non Shift-JIS charactors and the compiler stops compiling with C4819. To fix the errors, remove non-ASCII charactors. --- googlemock/include/gmock/gmock-generated-function-mockers.h | 8 ++++---- googlemock/include/gmock/gmock-generated-function-mockers.h.pump | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h b/googlemock/include/gmock/gmock-generated-function-mockers.h index 126c48c..b8bf7a5 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h @@ -352,21 +352,21 @@ class FunctionMocker : public // // class MockClass { // // Overload 1 -// MockSpec gmock_GetName() { … } +// MockSpec gmock_GetName() { ... } // // Overload 2. Declared const so that the compiler will generate an // // error when trying to resolve between this and overload 4 in // // 'gmock_GetName(WithoutMatchers(), nullptr)'. // MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { +// const WithoutMatchers&, const Function*) const { // // Removes const from this, calls overload 1 // return AdjustConstness_(this)->gmock_GetName(); // } // // // Overload 3 -// const string& gmock_GetName() const { … } +// const string& gmock_GetName() const { ... } // // Overload 4 // MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { +// const WithoutMatchers&, const Function*) const { // // Does not remove const, calls overload 3 // return AdjustConstness_const(this)->gmock_GetName(); // } diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump index efcb3e8..6426d9a 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump @@ -114,21 +114,21 @@ class FunctionMocker : public // // class MockClass { // // Overload 1 -// MockSpec gmock_GetName() { … } +// MockSpec gmock_GetName() { ... } // // Overload 2. Declared const so that the compiler will generate an // // error when trying to resolve between this and overload 4 in // // 'gmock_GetName(WithoutMatchers(), nullptr)'. // MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { +// const WithoutMatchers&, const Function*) const { // // Removes const from this, calls overload 1 // return AdjustConstness_(this)->gmock_GetName(); // } // // // Overload 3 -// const string& gmock_GetName() const { … } +// const string& gmock_GetName() const { ... } // // Overload 4 // MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { +// const WithoutMatchers&, const Function*) const { // // Does not remove const, calls overload 3 // return AdjustConstness_const(this)->gmock_GetName(); // } -- cgit v0.12 From 4c417877648f5f240aecead1c19d7c1fd340423b Mon Sep 17 00:00:00 2001 From: Derek Mauro Date: Tue, 10 Jul 2018 14:30:42 -0400 Subject: Adds stacktrace support from Abseil to Google Test This change adds the ability to generate stacktraces in Google Test on both failures of assertions/expectations and on crashes. The stacktrace support is conditionally available only when using Abseil with Google Test. To use this support, run the test under Bazel with a command like this: bazel test --define absl=1 --test_env=GTEST_INSTALL_FAILURE_SIGNAL_HANDLER=1 //path/to/your:test The "--define absl=1" part enables stacktraces on assertion/expectation failures. The "--test_env=GTEST_INSTALL_FAILURE_SIGNAL_HANDLER=1" part enables the signal handler that logs a stacktrace in the event of a crash (this also requires the "--define absl=1" part). This is not the default since it may interfere with existing tests. --- BUILD.bazel | 38 ++-- googletest/src/gtest-internal-inl.h | 10 + googletest/src/gtest.cc | 86 ++++++++- googletest/test/BUILD.bazel | 62 +++++-- googletest/test/gtest_output_test.py | 14 +- googletest/test/gtest_output_test_golden_lin.txt | 222 ++++++++++++++++++++++- googletest/test/gtest_xml_output_unittest.py | 7 +- 7 files changed, 391 insertions(+), 48 deletions(-) diff --git a/BUILD.bazel b/BUILD.bazel index 6d82829..2ed3bf6 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -38,7 +38,7 @@ licenses(["notice"]) config_setting( name = "windows", - values = { "cpu": "x64_windows" }, + values = {"cpu": "x64_windows"}, ) config_setting( @@ -51,7 +51,6 @@ config_setting( values = {"define": "absl=1"}, ) - # Google Test including Google Mock cc_library( name = "gtest", @@ -70,7 +69,7 @@ cc_library( "googlemock/src/gmock_main.cc", ], ), - hdrs =glob([ + hdrs = glob([ "googletest/include/gtest/*.h", "googlemock/include/gmock/*.h", ]), @@ -81,6 +80,14 @@ cc_library( "//conditions:default": ["-pthread"], }, ), + defines = select( + { + ":has_absl": [ + "GTEST_HAS_ABSL=1", + ], + "//conditions:default": [], + }, + ), includes = [ "googlemock", "googlemock/include", @@ -94,21 +101,18 @@ cc_library( "-pthread", ], }), - defines = select ({ - ":has_absl": [ - "GTEST_HAS_ABSL=1", - ], - "//conditions:default": [], - } + deps = select( + { + ":has_absl": [ + "@com_google_absl//absl/debugging:failure_signal_handler", + "@com_google_absl//absl/debugging:stacktrace", + "@com_google_absl//absl/debugging:symbolize", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:optional", + ], + "//conditions:default": [], + }, ), - deps = select ({ - ":has_absl": [ - "@com_google_absl//absl/types:optional", - "@com_google_absl//absl/strings" - ], - "//conditions:default": [], - } - ) ) cc_library( diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index e77c8b6..c5a4265 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -446,6 +446,16 @@ class OsStackTraceGetter : public OsStackTraceGetterInterface { virtual void UponLeavingGTest(); private: +#if GTEST_HAS_ABSL + Mutex mutex_; // Protects all internal state. + + // We save the stack frame below the frame that calls user code. + // We do this because the address of the frame immediately below + // the user code changes between the call to UponLeavingGTest() + // and any calls to the stack trace code from within the user code. + void* caller_frame_ = nullptr; +#endif // GTEST_HAS_ABSL + GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); }; diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index ce6c07f..9c25c99 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -139,6 +139,13 @@ # define vsnprintf _vsnprintf #endif // GTEST_OS_WINDOWS +#if GTEST_HAS_ABSL +#include "absl/debugging/failure_signal_handler.h" +#include "absl/debugging/stacktrace.h" +#include "absl/debugging/symbolize.h" +#include "absl/strings/str_cat.h" +#endif // GTEST_HAS_ABSL + namespace testing { using internal::CountIf; @@ -228,6 +235,13 @@ GTEST_DEFINE_string_( "exclude). A test is run if it matches one of the positive " "patterns and does not match any of the negative patterns."); +GTEST_DEFINE_bool_( + install_failure_signal_handler, + internal::BoolFromGTestEnv("install_failure_signal_handler", false), + "If true and supported on the current platform, " GTEST_NAME_ " should " + "install a signal handler that dumps debugging information when fatal " + "signals are raised."); + GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them."); @@ -4243,12 +4257,67 @@ void StreamingListener::SocketWriter::MakeConnection() { const char* const OsStackTraceGetterInterface::kElidedFramesMarker = "... " GTEST_NAME_ " internal frames ..."; -std::string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/, - int /*skip_count*/) { +std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) + GTEST_LOCK_EXCLUDED_(mutex_) { +#if GTEST_HAS_ABSL + std::string result; + + if (max_depth <= 0) { + return result; + } + + max_depth = std::min(max_depth, kMaxStackTraceDepth); + + std::vector raw_stack(max_depth); + // Skips the frames requested by the caller, plus this function. + const int raw_stack_size = + absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1); + + void* caller_frame = nullptr; + { + MutexLock lock(&mutex_); + caller_frame = caller_frame_; + } + + for (int i = 0; i < raw_stack_size; ++i) { + if (raw_stack[i] == caller_frame && + !GTEST_FLAG(show_internal_stack_frames)) { + // Add a marker to the trace and stop adding frames. + absl::StrAppend(&result, kElidedFramesMarker, "\n"); + break; + } + + char tmp[1024]; + const char* symbol = "(unknown)"; + if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) { + symbol = tmp; + } + + char line[1024]; + snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol); + result += line; + } + + return result; + +#else // !GTEST_HAS_ABSL + static_cast(max_depth); + static_cast(skip_count); return ""; +#endif // GTEST_HAS_ABSL } -void OsStackTraceGetter::UponLeavingGTest() {} +void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) { +#if GTEST_HAS_ABSL + void* caller_frame = nullptr; + if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) { + caller_frame = nullptr; + } + + MutexLock lock(&mutex_); + caller_frame_ = caller_frame; +#endif // GTEST_HAS_ABSL +} // A helper class that creates the premature-exit file in its // constructor and deletes the file in its destructor. @@ -4865,6 +4934,13 @@ void UnitTestImpl::PostFlagParsingInit() { // Configures listeners for streaming test results to the specified server. ConfigureStreamingOutput(); #endif // GTEST_CAN_STREAM_RESULTS_ + +#if GTEST_HAS_ABSL + if (GTEST_FLAG(install_failure_signal_handler)) { + absl::FailureSignalHandlerOptions options; + absl::InstallFailureSignalHandler(options); + } +#endif // GTEST_HAS_ABSL } } @@ -5769,6 +5845,10 @@ void InitGoogleTestImpl(int* argc, CharType** argv) { g_argvs.push_back(StreamableToString(argv[i])); } +#if GTEST_HAS_ABSL + absl::InitializeSymbolizer(g_argvs[0].c_str()); +#endif // GTEST_HAS_ABSL + ParseGoogleTestFlagsOnly(argc, argv); GetUnitTestImpl()->PostFlagParsingInit(); } diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 365a855..405feee 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -34,35 +34,48 @@ licenses(["notice"]) -""" gtest own tests """ +config_setting( + name = "windows", + values = {"cpu": "x64_windows"}, +) + +config_setting( + name = "windows_msvc", + values = {"cpu": "x64_windows_msvc"}, +) + +config_setting( + name = "has_absl", + values = {"define": "absl=1"}, +) #on windows exclude gtest-tuple.h and gtest-tuple_test.cc cc_test( name = "gtest_all_test", size = "small", - srcs = glob( - include = [ - "gtest-*.cc", - "*.h", - "googletest/include/gtest/**/*.h", - ], - exclude = [ - "gtest-unittest-api_test.cc", - "gtest-tuple_test.cc", - "googletest/src/gtest-all.cc", - "gtest_all_test.cc", - "gtest-death-test_ex_test.cc", - "gtest-listener_test.cc", - "gtest-unittest-api_test.cc", - "gtest-param-test_test.cc", - ], - ) + select({ + srcs = glob( + include = [ + "gtest-*.cc", + "*.h", + "googletest/include/gtest/**/*.h", + ], + exclude = [ + "gtest-unittest-api_test.cc", + "gtest-tuple_test.cc", + "googletest/src/gtest-all.cc", + "gtest_all_test.cc", + "gtest-death-test_ex_test.cc", + "gtest-listener_test.cc", + "gtest-unittest-api_test.cc", + "gtest-param-test_test.cc", + ], + ) + select({ "//:windows": [], "//:windows_msvc": [], "//conditions:default": [ "gtest-tuple_test.cc", ], - }), + }), copts = select({ "//:windows": ["-DGTEST_USE_OWN_TR1_TUPLE=0"], "//:windows_msvc": ["-DGTEST_USE_OWN_TR1_TUPLE=0"], @@ -135,7 +148,6 @@ py_library( name = "gtest_test_utils", testonly = 1, srcs = ["gtest_test_utils.py"], - ) cc_binary( @@ -144,6 +156,7 @@ cc_binary( srcs = ["gtest_help_test_.cc"], deps = ["//:gtest_main"], ) + py_test( name = "gtest_help_test", size = "small", @@ -163,6 +176,10 @@ py_test( name = "gtest_output_test", size = "small", srcs = ["gtest_output_test.py"], + args = select({ + ":has_absl": [], + "//conditions:default": ["--no_stacktrace_support"], + }), data = [ "gtest_output_test_golden_lin.txt", ":gtest_output_test_", @@ -176,6 +193,7 @@ cc_binary( srcs = ["gtest_color_test_.cc"], deps = ["//:gtest"], ) + py_test( name = "gtest_color_test", size = "small", @@ -327,6 +345,10 @@ py_test( "gtest_xml_output_unittest.py", "gtest_xml_test_utils.py", ], + args = select({ + ":has_absl": [], + "//conditions:default": ["--no_stacktrace_support"], + }), data = [ # We invoke gtest_no_test_unittest to verify the XML output # when the test program contains no test definition. diff --git a/googletest/test/gtest_output_test.py b/googletest/test/gtest_output_test.py index f83d3be..63763b9 100755 --- a/googletest/test/gtest_output_test.py +++ b/googletest/test/gtest_output_test.py @@ -52,6 +52,9 @@ import gtest_test_utils GENGOLDEN_FLAG = '--gengolden' CATCH_EXCEPTIONS_ENV_VAR_NAME = 'GTEST_CATCH_EXCEPTIONS' +# The flag indicating stacktraces are not supported +NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' + IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' IS_WINDOWS = os.name == 'nt' @@ -252,13 +255,12 @@ test_list = GetShellCommandOutput(COMMAND_LIST_TESTS) SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list -SUPPORTS_STACK_TRACES = IS_LINUX +SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and SUPPORTS_TYPED_TESTS and SUPPORTS_THREADS and - SUPPORTS_STACK_TRACES and - not IS_WINDOWS) + SUPPORTS_STACK_TRACES) class GTestOutputTest(gtest_test_utils.TestCase): def RemoveUnsupportedTests(self, test_output): @@ -325,7 +327,11 @@ class GTestOutputTest(gtest_test_utils.TestCase): if __name__ == '__main__': - if sys.argv[1:] == [GENGOLDEN_FLAG]: + if NO_STACKTRACE_SUPPORT_FLAG in sys.argv: + # unittest.main() can't handle unknown flags + sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG) + + if GENGOLDEN_FLAG in sys.argv: if CAN_GENERATE_GOLDEN_FILE: output = GetOutputOfAllCommands() golden_file = open(GOLDEN_PATH, 'wb') diff --git a/googletest/test/gtest_output_test_golden_lin.txt b/googletest/test/gtest_output_test_golden_lin.txt index cbcb720..02a77a8 100644 --- a/googletest/test/gtest_output_test_golden_lin.txt +++ b/googletest/test/gtest_output_test_golden_lin.txt @@ -4,10 +4,14 @@ gtest_output_test_.cc:#: Failure Value of: false Actual: false Expected: true +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Expected equality of these values: 2 3 +Stack trace: (omitted) + [==========] Running 68 tests from 30 test cases. [----------] Global test environment set-up. FooEnvironment::SetUp() called. @@ -40,12 +44,16 @@ Expected equality of these values: Which is: "\"Line" actual Which is: "actual \"string\"" +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Expected equality of these values: golden Which is: "\"Line" actual Which is: "actual \"string\"" +Stack trace: (omitted) + [ FAILED ] NonfatalFailureTest.EscapesStringOperands [ RUN ] NonfatalFailureTest.DiffForLongStrings gtest_output_test_.cc:#: Failure @@ -58,6 +66,8 @@ With diff: -\"Line\0 1\" Line 2 +Stack trace: (omitted) + [ FAILED ] NonfatalFailureTest.DiffForLongStrings [----------] 3 tests from FatalFailureTest [ RUN ] FatalFailureTest.FatalFailureInSubroutine @@ -67,6 +77,8 @@ Expected equality of these values: 1 x Which is: 2 +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.FatalFailureInSubroutine [ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine (expecting a failure that x should be 1) @@ -75,6 +87,8 @@ Expected equality of these values: 1 x Which is: 2 +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine [ RUN ] FatalFailureTest.NonfatalFailureInSubroutine (expecting a failure on false) @@ -82,6 +96,8 @@ gtest_output_test_.cc:#: Failure Value of: false Actual: false Expected: true +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine [----------] 1 test from LoggingTest [ RUN ] LoggingTest.InterleavingLoggingAndAssertions @@ -90,10 +106,14 @@ i == 0 i == 1 gtest_output_test_.cc:#: Failure Expected: (3) >= (a[i]), actual: 3 vs 9 +Stack trace: (omitted) + i == 2 i == 3 gtest_output_test_.cc:#: Failure Expected: (3) >= (a[i]), actual: 3 vs 6 +Stack trace: (omitted) + [ FAILED ] LoggingTest.InterleavingLoggingAndAssertions [----------] 7 tests from SCOPED_TRACETest [ RUN ] SCOPED_TRACETest.AcceptedValues @@ -105,20 +125,28 @@ gtest_output_test_.cc:#: (null) gtest_output_test_.cc:#: 1337 gtest_output_test_.cc:#: std::string gtest_output_test_.cc:#: literal string +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.AcceptedValues [ RUN ] SCOPED_TRACETest.ObeysScopes (expected to fail) gtest_output_test_.cc:#: Failure Failed This failure is expected, and shouldn't have a trace. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed This failure is expected, and should have a trace. Google Test trace: gtest_output_test_.cc:#: Expected trace +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed This failure is expected, and shouldn't have a trace. +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.ObeysScopes [ RUN ] SCOPED_TRACETest.WorksInLoop (expected to fail) @@ -129,6 +157,8 @@ Expected equality of these values: Which is: 1 Google Test trace: gtest_output_test_.cc:#: i = 1 +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Expected equality of these values: 1 @@ -136,6 +166,8 @@ Expected equality of these values: Which is: 2 Google Test trace: gtest_output_test_.cc:#: i = 2 +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.WorksInLoop [ RUN ] SCOPED_TRACETest.WorksInSubroutine (expected to fail) @@ -146,6 +178,8 @@ Expected equality of these values: Which is: 1 Google Test trace: gtest_output_test_.cc:#: n = 1 +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Expected equality of these values: 1 @@ -153,6 +187,8 @@ Expected equality of these values: Which is: 2 Google Test trace: gtest_output_test_.cc:#: n = 2 +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.WorksInSubroutine [ RUN ] SCOPED_TRACETest.CanBeNested (expected to fail) @@ -164,6 +200,8 @@ Expected equality of these values: Google Test trace: gtest_output_test_.cc:#: n = 2 gtest_output_test_.cc:#: +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.CanBeNested [ RUN ] SCOPED_TRACETest.CanBeRepeated (expected to fail) @@ -172,12 +210,16 @@ Failed This failure is expected, and should contain trace point A. Google Test trace: gtest_output_test_.cc:#: A +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure 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 +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed This failure is expected, and should contain trace point A, B, and C. @@ -185,6 +227,8 @@ Google Test trace: gtest_output_test_.cc:#: C gtest_output_test_.cc:#: B gtest_output_test_.cc:#: A +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed This failure is expected, and should contain trace point A, B, and D. @@ -192,6 +236,8 @@ Google Test trace: gtest_output_test_.cc:#: D gtest_output_test_.cc:#: B gtest_output_test_.cc:#: A +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.CanBeRepeated [ RUN ] SCOPED_TRACETest.WorksConcurrently (expecting 6 failures) @@ -200,27 +246,39 @@ Failed Expected failure #1 (in thread B, only trace B alive). Google Test trace: gtest_output_test_.cc:#: Trace B +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #2 (in thread A, trace A & B both alive). Google Test trace: gtest_output_test_.cc:#: Trace A +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #3 (in thread B, trace A & B both alive). Google Test trace: gtest_output_test_.cc:#: Trace B +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #4 (in thread B, only trace A alive). +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #5 (in thread A, only trace A alive). Google Test trace: gtest_output_test_.cc:#: Trace A +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #6 (in thread A, no trace alive). +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.WorksConcurrently [----------] 1 test from ScopedTraceTest [ RUN ] ScopedTraceTest.WithExplicitFileAndLine @@ -229,6 +287,8 @@ Failed Check that the trace is attached to a particular location. Google Test trace: explicit_file.cc:123: expected trace message +Stack trace: (omitted) + [ FAILED ] ScopedTraceTest.WithExplicitFileAndLine [----------] 1 test from NonFatalFailureInFixtureConstructorTest [ RUN ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor @@ -236,18 +296,28 @@ explicit_file.cc:123: expected trace message gtest_output_test_.cc:#: Failure Failed Expected failure #1, in the test fixture c'tor. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #2, in SetUp(). +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #3, in the test body. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #4, in TearDown. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #5, in the test fixture d'tor. +Stack trace: (omitted) + [ FAILED ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor [----------] 1 test from FatalFailureInFixtureConstructorTest [ RUN ] FatalFailureInFixtureConstructorTest.FailureInConstructor @@ -255,9 +325,13 @@ Expected failure #5, in the test fixture d'tor. gtest_output_test_.cc:#: Failure Failed Expected failure #1, in the test fixture c'tor. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #2, in the test fixture d'tor. +Stack trace: (omitted) + [ FAILED ] FatalFailureInFixtureConstructorTest.FailureInConstructor [----------] 1 test from NonFatalFailureInSetUpTest [ RUN ] NonFatalFailureInSetUpTest.FailureInSetUp @@ -265,15 +339,23 @@ Expected failure #2, in the test fixture d'tor. gtest_output_test_.cc:#: Failure Failed Expected failure #1, in SetUp(). +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #2, in the test function. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #3, in TearDown(). +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #4, in the test fixture d'tor. +Stack trace: (omitted) + [ FAILED ] NonFatalFailureInSetUpTest.FailureInSetUp [----------] 1 test from FatalFailureInSetUpTest [ RUN ] FatalFailureInSetUpTest.FailureInSetUp @@ -281,18 +363,26 @@ Expected failure #4, in the test fixture d'tor. gtest_output_test_.cc:#: Failure Failed Expected failure #1, in SetUp(). +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #2, in TearDown(). +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #3, in the test fixture d'tor. +Stack trace: (omitted) + [ FAILED ] FatalFailureInSetUpTest.FailureInSetUp [----------] 1 test from AddFailureAtTest [ RUN ] AddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber foo.cc:42: Failure Failed Expected failure in foo.cc +Stack trace: (omitted) + [ FAILED ] AddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber [----------] 4 tests from MixedUpTestCaseTest [ RUN ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo @@ -309,6 +399,8 @@ 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. +Stack trace: (omitted) + [ FAILED ] MixedUpTestCaseTest.ThisShouldFail [ RUN ] MixedUpTestCaseTest.ThisShouldFailToo gtest.cc:#: Failure @@ -320,6 +412,8 @@ 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. +Stack trace: (omitted) + [ FAILED ] MixedUpTestCaseTest.ThisShouldFailToo [----------] 2 tests from MixedUpTestCaseWithSameTestNameTest [ RUN ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail @@ -334,6 +428,8 @@ 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. +Stack trace: (omitted) + [ 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 @@ -348,6 +444,8 @@ 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. +Stack trace: (omitted) + [ 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 @@ -362,6 +460,8 @@ 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. +Stack trace: (omitted) + [ FAILED ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail [----------] 8 tests from ExpectNonfatalFailureTest [ RUN ] ExpectNonfatalFailureTest.CanReferenceGlobalVariables @@ -375,6 +475,8 @@ case. gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure [ RUN ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures (expecting a failure) @@ -384,10 +486,16 @@ Expected: 1 non-fatal failure gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure 1. +Stack trace: (omitted) + gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure 2. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures [ RUN ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure @@ -398,6 +506,10 @@ Expected: 1 non-fatal failure gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure [ RUN ] ExpectNonfatalFailureTest.FailsWhenStatementReturns @@ -405,12 +517,16 @@ Expected fatal failure. gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementReturns [ RUN ] ExpectNonfatalFailureTest.FailsWhenStatementThrows (expecting a failure) gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementThrows [----------] 8 tests from ExpectFatalFailureTest [ RUN ] ExpectFatalFailureTest.CanReferenceGlobalVariables @@ -424,6 +540,8 @@ Expected: 1 non-fatal failure gtest.cc:#: Failure Expected: 1 fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure [ RUN ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures (expecting a failure) @@ -433,10 +551,16 @@ Expected: 1 fatal failure gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures [ RUN ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure @@ -447,6 +571,10 @@ Expected: 1 fatal failure gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure [ RUN ] ExpectFatalFailureTest.FailsWhenStatementReturns @@ -454,12 +582,16 @@ Expected non-fatal failure. gtest.cc:#: Failure Expected: 1 fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectFatalFailureTest.FailsWhenStatementReturns [ RUN ] ExpectFatalFailureTest.FailsWhenStatementThrows (expecting a failure) gtest.cc:#: Failure Expected: 1 fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectFatalFailureTest.FailsWhenStatementThrows [----------] 2 tests from TypedTest/0, where TypeParam = int [ RUN ] TypedTest/0.Success @@ -471,6 +603,8 @@ Expected equality of these values: TypeParam() Which is: 0 Expected failure +Stack trace: (omitted) + [ FAILED ] TypedTest/0.Failure, where TypeParam = int [----------] 2 tests from Unsigned/TypedTestP/0, where TypeParam = unsigned char [ RUN ] Unsigned/TypedTestP/0.Success @@ -483,8 +617,10 @@ Expected equality of these values: TypeParam() Which is: '\0' Expected failure +Stack trace: (omitted) + [ FAILED ] Unsigned/TypedTestP/0.Failure, where TypeParam = unsigned char -[----------] 2 tests from Unsigned/TypedTestP/1, where TypeParam = unsigned +[----------] 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 @@ -495,7 +631,9 @@ Expected equality of these values: TypeParam() Which is: 0 Expected failure -[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned +Stack trace: (omitted) + +[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int [----------] 4 tests from ExpectFailureTest [ RUN ] ExpectFailureTest.ExpectFatalFailure (expecting 1 failure) @@ -504,6 +642,10 @@ Expected: 1 fatal failure Actual: gtest_output_test_.cc:#: Success: Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -512,6 +654,10 @@ Expected: 1 fatal failure gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -520,6 +666,10 @@ Expected: 1 fatal failure containing "Some other fatal failure expected." gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectFailureTest.ExpectFatalFailure [ RUN ] ExpectFailureTest.ExpectNonFatalFailure @@ -529,6 +679,10 @@ Expected: 1 non-fatal failure Actual: gtest_output_test_.cc:#: Success: Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -537,6 +691,10 @@ Expected: 1 non-fatal failure gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -545,6 +703,10 @@ Expected: 1 non-fatal failure containing "Some other non-fatal failure." gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectFailureTest.ExpectNonFatalFailure [ RUN ] ExpectFailureTest.ExpectFatalFailureOnAllThreads @@ -554,6 +716,10 @@ Expected: 1 fatal failure Actual: gtest_output_test_.cc:#: Success: Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -562,6 +728,10 @@ Expected: 1 fatal failure gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -570,6 +740,10 @@ Expected: 1 fatal failure containing "Some other fatal failure expected." gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectFailureTest.ExpectFatalFailureOnAllThreads [ RUN ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads @@ -579,6 +753,10 @@ Expected: 1 non-fatal failure Actual: gtest_output_test_.cc:#: Success: Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -587,6 +765,10 @@ Expected: 1 non-fatal failure gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -595,6 +777,10 @@ Expected: 1 non-fatal failure containing "Some other non-fatal failure." gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads [----------] 2 tests from ExpectFailureWithThreadsTest @@ -603,18 +789,26 @@ Expected non-fatal failure. gtest_output_test_.cc:#: Failure Failed Expected fatal failure. +Stack trace: (omitted) + gtest.cc:#: Failure Expected: 1 fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectFailureWithThreadsTest.ExpectFatalFailure [ RUN ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure (expecting 2 failures) gtest_output_test_.cc:#: Failure Failed Expected non-fatal failure. +Stack trace: (omitted) + gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure [----------] 1 test from ScopedFakeTestPartResultReporterTest [ RUN ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread @@ -622,9 +816,13 @@ Expected: 1 non-fatal failure gtest_output_test_.cc:#: Failure Failed Expected fatal failure. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected non-fatal failure. +Stack trace: (omitted) + [ FAILED ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread [----------] 1 test from PrintingFailingParams/FailingParamTest [ RUN ] PrintingFailingParams/FailingParamTest.Fails/0 @@ -633,6 +831,8 @@ Expected equality of these values: 1 GetParam() Which is: 2 +Stack trace: (omitted) + [ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 [----------] 2 tests from PrintingStrings/ParamTest [ RUN ] PrintingStrings/ParamTest.Success/a @@ -644,16 +844,22 @@ Expected equality of these values: GetParam() Which is: "a" Expected failure +Stack trace: (omitted) + [ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a" [----------] Global test environment tear-down BarEnvironment::TearDown() called. gtest_output_test_.cc:#: Failure Failed Expected non-fatal failure. +Stack trace: (omitted) + FooEnvironment::TearDown() called. gtest_output_test_.cc:#: Failure Failed Expected fatal failure. +Stack trace: (omitted) + [==========] 68 tests from 30 test cases ran. [ PASSED ] 22 tests. [ FAILED ] 46 tests, listed below: @@ -693,7 +899,7 @@ Expected fatal failure. [ 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 +[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int [ FAILED ] ExpectFailureTest.ExpectFatalFailure [ FAILED ] ExpectFailureTest.ExpectNonFatalFailure [ FAILED ] ExpectFailureTest.ExpectFatalFailureOnAllThreads @@ -718,6 +924,8 @@ Expected equality of these values: 1 x Which is: 2 +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.FatalFailureInSubroutine (? ms) [ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine (expecting a failure that x should be 1) @@ -726,6 +934,8 @@ Expected equality of these values: 1 x Which is: 2 +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine (? ms) [ RUN ] FatalFailureTest.NonfatalFailureInSubroutine (expecting a failure on false) @@ -733,6 +943,8 @@ gtest_output_test_.cc:#: Failure Value of: false Actual: false Expected: true +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine (? ms) [----------] 3 tests from FatalFailureTest (? ms total) @@ -743,10 +955,14 @@ i == 0 i == 1 gtest_output_test_.cc:#: Failure Expected: (3) >= (a[i]), actual: 3 vs 9 +Stack trace: (omitted) + i == 2 i == 3 gtest_output_test_.cc:#: Failure Expected: (3) >= (a[i]), actual: 3 vs 6 +Stack trace: (omitted) + [ FAILED ] LoggingTest.InterleavingLoggingAndAssertions (? ms) [----------] 1 test from LoggingTest (? ms total) diff --git a/googletest/test/gtest_xml_output_unittest.py b/googletest/test/gtest_xml_output_unittest.py index 6ffb6e3..faedd4e 100755 --- a/googletest/test/gtest_xml_output_unittest.py +++ b/googletest/test/gtest_xml_output_unittest.py @@ -47,17 +47,22 @@ GTEST_OUTPUT_FLAG = '--gtest_output' GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml' GTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_' +# The flag indicating stacktraces are not supported +NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' + # The environment variables for test sharding. TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS' SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX' SHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE' -SUPPORTS_STACK_TRACES = False +SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv if SUPPORTS_STACK_TRACES: STACK_TRACE_TEMPLATE = '\nStack trace:\n*' else: STACK_TRACE_TEMPLATE = '' + # unittest.main() can't handle unknown flags + sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG) EXPECTED_NON_EMPTY_XML = """ -- cgit v0.12 From d772e2039b2dd4ebd137659e8d6297e6cf04697e Mon Sep 17 00:00:00 2001 From: Derek Mauro Date: Tue, 10 Jul 2018 15:39:23 -0400 Subject: Pass the --no_stacktrace_support argument to the CMake tests This does the same thing to the CMake tests that is done to the Bazel tests, and now makes the CMake tests pass. --- googletest/CMakeLists.txt | 4 ++-- googletest/cmake/internal_utils.cmake | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index b09c46e..2e412d7 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -284,7 +284,7 @@ if (gtest_build_tests) py_test(gtest_list_tests_unittest) cxx_executable(gtest_output_test_ test gtest) - py_test(gtest_output_test) + py_test(gtest_output_test --no_stacktrace_support) cxx_executable(gtest_shuffle_test_ test gtest) py_test(gtest_shuffle_test) @@ -307,6 +307,6 @@ if (gtest_build_tests) py_test(gtest_json_outfiles_test) cxx_executable(gtest_xml_output_unittest_ test gtest) - py_test(gtest_xml_output_unittest) + py_test(gtest_xml_output_unittest --no_stacktrace_support) py_test(gtest_json_output_unittest) endif() diff --git a/googletest/cmake/internal_utils.cmake b/googletest/cmake/internal_utils.cmake index 6448918..be7af38 100644 --- a/googletest/cmake/internal_utils.cmake +++ b/googletest/cmake/internal_utils.cmake @@ -257,14 +257,14 @@ function(py_test name) add_test( NAME ${name} COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py - --build_dir=${CMAKE_CURRENT_BINARY_DIR}/$) + --build_dir=${CMAKE_CURRENT_BINARY_DIR}/$ ${ARGN}) else (CMAKE_CONFIGURATION_TYPES) # Single-configuration build generators like Makefile generators # don't have subdirs below CMAKE_CURRENT_BINARY_DIR. add_test( NAME ${name} COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py - --build_dir=${CMAKE_CURRENT_BINARY_DIR}) + --build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN}) endif (CMAKE_CONFIGURATION_TYPES) else (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 3.1) # ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can @@ -274,7 +274,7 @@ function(py_test name) add_test( ${name} ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py - --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE}) + --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN}) endif (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 3.1) endif(PYTHONINTERP_FOUND) endfunction() -- cgit v0.12 From 93bfdde0eeac83fb51b856dc4dc9c38c408b0ee0 Mon Sep 17 00:00:00 2001 From: Adrian Moran Date: Wed, 11 Jul 2018 14:59:01 +0200 Subject: Fix issue #1654. Signed-off-by: Adrian Moran --- googlemock/test/gmock_ex_test.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc index 3afed86..8c83890 100644 --- a/googlemock/test/gmock_ex_test.cc +++ b/googlemock/test/gmock_ex_test.cc @@ -37,7 +37,9 @@ namespace { using testing::HasSubstr; +#if GTEST_HAS_EXCEPTIONS using testing::internal::GoogleTestFailureException; +#endif // A type that cannot be default constructed. class NonDefaultConstructible { -- cgit v0.12 From 0acdf796420e4562ef7399b8610d23eda3256a5a Mon Sep 17 00:00:00 2001 From: Adrian Moran Date: Thu, 12 Jul 2018 15:10:08 +0200 Subject: Avoid full test in no exceptions are enabled. Signed-off-by: Adrian Moran --- googlemock/test/gmock_ex_test.cc | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc index 8c83890..5a299da 100644 --- a/googlemock/test/gmock_ex_test.cc +++ b/googlemock/test/gmock_ex_test.cc @@ -31,15 +31,14 @@ // Tests Google Mock's functionality that depends on exceptions. +#if GTEST_HAS_EXCEPTIONS #include "gmock/gmock.h" #include "gtest/gtest.h" namespace { using testing::HasSubstr; -#if GTEST_HAS_EXCEPTIONS using testing::internal::GoogleTestFailureException; -#endif // A type that cannot be default constructed. class NonDefaultConstructible { @@ -54,7 +53,6 @@ class MockFoo { MOCK_METHOD0(GetNonDefaultConstructible, NonDefaultConstructible()); }; -#if GTEST_HAS_EXCEPTIONS TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { MockFoo mock; @@ -78,6 +76,5 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { } } -#endif - } // unnamed namespace +#endif -- cgit v0.12 From 6c7878a151f05d64f675b800b054c5fc43f3dd6d Mon Sep 17 00:00:00 2001 From: Derek Mauro Date: Thu, 12 Jul 2018 13:46:50 -0400 Subject: Adds the UniversalPrinter for absl::variant. --- BUILD.bazel | 36 ++++++++++++++++--------------- googletest/include/gtest/gtest-printers.h | 23 ++++++++++++++++++++ 2 files changed, 42 insertions(+), 17 deletions(-) diff --git a/BUILD.bazel b/BUILD.bazel index 6d82829..f6dccd3 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -38,7 +38,7 @@ licenses(["notice"]) config_setting( name = "windows", - values = { "cpu": "x64_windows" }, + values = {"cpu": "x64_windows"}, ) config_setting( @@ -51,7 +51,6 @@ config_setting( values = {"define": "absl=1"}, ) - # Google Test including Google Mock cc_library( name = "gtest", @@ -70,7 +69,7 @@ cc_library( "googlemock/src/gmock_main.cc", ], ), - hdrs =glob([ + hdrs = glob([ "googletest/include/gtest/*.h", "googlemock/include/gmock/*.h", ]), @@ -81,6 +80,14 @@ cc_library( "//conditions:default": ["-pthread"], }, ), + defines = select( + { + ":has_absl": [ + "GTEST_HAS_ABSL=1", + ], + "//conditions:default": [], + }, + ), includes = [ "googlemock", "googlemock/include", @@ -94,21 +101,16 @@ cc_library( "-pthread", ], }), - defines = select ({ - ":has_absl": [ - "GTEST_HAS_ABSL=1", - ], - "//conditions:default": [], - } + deps = select( + { + ":has_absl": [ + "@com_google_absl//absl/types:optional", + "@com_google_absl//absl/types:variant", + "@com_google_absl//absl/strings", + ], + "//conditions:default": [], + }, ), - deps = select ({ - ":has_absl": [ - "@com_google_absl//absl/types:optional", - "@com_google_absl//absl/strings" - ], - "//conditions:default": [], - } - ) ) cc_library( diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index 373946b..66d54b9 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -114,6 +114,7 @@ #if GTEST_HAS_ABSL #include "absl/strings/string_view.h" #include "absl/types/optional.h" +#include "absl/types/variant.h" #endif // GTEST_HAS_ABSL namespace testing { @@ -787,6 +788,28 @@ class UniversalPrinter<::absl::optional> { } }; +// Printer for absl::variant + +template +class UniversalPrinter<::absl::variant> { + public: + static void Print(const ::absl::variant& value, ::std::ostream* os) { + *os << '('; + absl::visit(Visitor{os}, value); + *os << ')'; + } + + private: + struct Visitor { + template + void operator()(const U& u) const { + *os << "'" << GetTypeName() << "' with value "; + UniversalPrint(u, os); + } + ::std::ostream* os; + }; +}; + #endif // GTEST_HAS_ABSL // UniversalPrintArray(begin, len, os) prints an array of 'len' -- cgit v0.12 From cbd07191f4b7a3498fd0d1d7c58c4c39cccb8fb8 Mon Sep 17 00:00:00 2001 From: Adrian Moran Date: Fri, 13 Jul 2018 08:53:03 +0200 Subject: Put ifdef guard after the includes. Signed-off-by: Adrian Moran --- googlemock/test/gmock_ex_test.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc index 5a299da..99268b3 100644 --- a/googlemock/test/gmock_ex_test.cc +++ b/googlemock/test/gmock_ex_test.cc @@ -31,10 +31,10 @@ // Tests Google Mock's functionality that depends on exceptions. -#if GTEST_HAS_EXCEPTIONS #include "gmock/gmock.h" #include "gtest/gtest.h" +#if GTEST_HAS_EXCEPTIONS namespace { using testing::HasSubstr; -- cgit v0.12 From 3a8d744030e165dc7bebf70e4fbc44831059a79b Mon Sep 17 00:00:00 2001 From: Loo Rong Jie Date: Fri, 13 Jul 2018 21:23:28 +0800 Subject: Disable MSVC function deprecation when using Clang --- googletest/include/gtest/internal/gtest-port.h | 20 ++++++++++++++++++-- googletest/src/gtest-port.cc | 4 ++-- googletest/src/gtest.cc | 4 ++-- googletest/test/gtest_unittest.cc | 4 ++-- 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index d5ec086..727b41f 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -325,6 +325,22 @@ # define GTEST_DISABLE_MSC_WARNINGS_POP_() #endif +// Clang on Windows does not understand MSVC's pragma warning. +// We need clang-specific way to disable function deprecation warning. +#ifdef __clang__ +# define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \ + _Pragma("clang diagnostic push") \ + _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \ + _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"") +#define GTEST_DISABLE_MSC_DEPRECATED_POP_() \ + _Pragma("clang diagnostic pop") +#else +# define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \ + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) +# define GTEST_DISABLE_MSC_DEPRECATED_POP_() \ + GTEST_DISABLE_MSC_WARNINGS_POP_() +#endif + #ifndef GTEST_LANG_CXX11 // gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when // -std={c,gnu}++{0x,11} is passed. The C++11 standard specifies a @@ -2483,7 +2499,7 @@ inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } // Functions deprecated by MSVC 8.0. -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */) +GTEST_DISABLE_MSC_DEPRECATED_PUSH_() inline const char* StrNCpy(char* dest, const char* src, size_t n) { return strncpy(dest, src, n); @@ -2531,7 +2547,7 @@ inline const char* GetEnv(const char* name) { #endif } -GTEST_DISABLE_MSC_WARNINGS_POP_() +GTEST_DISABLE_MSC_DEPRECATED_POP_() #if GTEST_OS_WINDOWS_MOBILE // Windows CE has no C library. The abort() function is used in diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index f8a0ad6..2ab2d25 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -942,7 +942,7 @@ GTestLog::~GTestLog() { // Disable Microsoft deprecation warnings for POSIX functions called from // this class (creat, dup, dup2, and close) -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) +GTEST_DISABLE_MSC_DEPRECATED_PUSH_() #if GTEST_HAS_STREAM_REDIRECTION @@ -1026,7 +1026,7 @@ class CapturedStream { GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); }; -GTEST_DISABLE_MSC_WARNINGS_POP_() +GTEST_DISABLE_MSC_DEPRECATED_POP_() static CapturedStream* g_captured_stderr = NULL; static CapturedStream* g_captured_stdout = NULL; diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 9c25c99..9a69080 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -860,9 +860,9 @@ TimeInMillis GetTimeInMillis() { // (deprecated function) there. // TODO(kenton@google.com): Use GetTickCount()? Or use // SystemTimeToFileTime() - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) + GTEST_DISABLE_MSC_DEPRECATED_PUSH_() _ftime64(&now); - GTEST_DISABLE_MSC_WARNINGS_POP_() + GTEST_DISABLE_MSC_DEPRECATED_POP_() return static_cast(now.time) * 1000 + now.millitm; #elif GTEST_HAS_GETTIMEOFDAY_ diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 39b6841..ab22031 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -444,10 +444,10 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test { virtual void SetUp() { saved_tz_ = NULL; - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* getenv, strdup: deprecated */) + GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */) if (getenv("TZ")) saved_tz_ = strdup(getenv("TZ")); - GTEST_DISABLE_MSC_WARNINGS_POP_() + GTEST_DISABLE_MSC_DEPRECATED_POP_() // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We // cannot use the local time zone because the function's output depends -- cgit v0.12 From 021c308069cce3751c8620c922c7a226836044b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20M=C5=82okosiewicz?= Date: Tue, 17 Jul 2018 00:49:31 +0200 Subject: Fix broken links to FAQ in primer.md --- googletest/docs/primer.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 9949658..15f2b08 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -197,7 +197,7 @@ objects, you should use `ASSERT_EQ`. When doing pointer comparisons use `*_EQ(ptr, nullptr)` and `*_NE(ptr, nullptr)` instead of `*_EQ(ptr, NULL)` and `*_NE(ptr, NULL)`. This is because `nullptr` is -typed while `NULL` is not. See [FAQ](faq#Why_does_googletest_support_EXPECT_EQ) +typed while `NULL` is not. See [FAQ](faq.md#why-does-google-test-support-expect_eqnull-ptr-and-assert_eqnull-ptr-but-not-expect_nenull-ptr-and-assert_nenull-ptr) for more details. If you're working with floating point numbers, you may want to use the floating @@ -322,7 +322,7 @@ To create a fixture: 1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read - this [FAQ](faq#CtorVsSetUp) entry. + this [FAQ](faq.md#should-i-use-the-constructordestructor-of-the-test-fixture-or-the-set-uptear-down-function) entry. 1. If needed, define subroutines for your tests to share. When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to -- cgit v0.12 From 65a49a73f0e7c059ad67d768c860bb296383fd56 Mon Sep 17 00:00:00 2001 From: duxiuxing Date: Tue, 17 Jul 2018 15:46:47 +0800 Subject: Fix warning C4819: The file contains a character that cannot be represented in the current code page (936). Save the file in Unicode format to prevent data loss --- .../gmock/gmock-generated-function-mockers.h | 4 +-- googlemock/include/gmock/gmock-spec-builders.h | 36 +++++++++++----------- .../include/gmock/internal/gmock-internal-utils.h | 2 +- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h b/googlemock/include/gmock/gmock-generated-function-mockers.h index 126c48c..d5417106 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h @@ -352,7 +352,7 @@ class FunctionMocker : public // // class MockClass { // // Overload 1 -// MockSpec gmock_GetName() { … } +// MockSpec gmock_GetName() { ... } // // Overload 2. Declared const so that the compiler will generate an // // error when trying to resolve between this and overload 4 in // // 'gmock_GetName(WithoutMatchers(), nullptr)'. @@ -363,7 +363,7 @@ class FunctionMocker : public // } // // // Overload 3 -// const string& gmock_GetName() const { … } +// const string& gmock_GetName() const { ... } // // Overload 4 // MockSpec gmock_GetName( // const WithoutMatchers&, const Function*) const { diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index cf1e7e2..090cff4 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -1854,22 +1854,22 @@ inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT // parameter. This technique may only be used for non-overloaded methods. // // // These are the same: -// ON_CALL(mock, NoArgsMethod()).WillByDefault(…); -// ON_CALL(mock, NoArgsMethod).WillByDefault(…); +// ON_CALL(mock, NoArgsMethod()).WillByDefault(...); +// ON_CALL(mock, NoArgsMethod).WillByDefault(...); // // // As are these: -// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(…); -// ON_CALL(mock, TwoArgsMethod).WillByDefault(…); +// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...); +// ON_CALL(mock, TwoArgsMethod).WillByDefault(...); // // // Can also specify args if you want, of course: -// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(…); +// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...); // // // Overloads work as long as you specify parameters: -// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(…); -// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(…); +// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...); +// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...); // // // Oops! Which overload did you want? -// ON_CALL(mock, OverloadedMethod).WillByDefault(…); +// ON_CALL(mock, OverloadedMethod).WillByDefault(...); // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous // // How this works: The mock class uses two overloads of the gmock_Method @@ -1877,28 +1877,28 @@ inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT // In the matcher list form, the macro expands to: // // // This statement: -// ON_CALL(mock, TwoArgsMethod(_, 45))… +// ON_CALL(mock, TwoArgsMethod(_, 45))... // -// // …expands to: -// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)… +// // ...expands to: +// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)... // |-------------v---------------||------------v-------------| // invokes first overload swallowed by operator() // -// // …which is essentially: -// mock.gmock_TwoArgsMethod(_, 45)… +// // ...which is essentially: +// mock.gmock_TwoArgsMethod(_, 45)... // // Whereas the form without a matcher list: // // // This statement: -// ON_CALL(mock, TwoArgsMethod)… +// ON_CALL(mock, TwoArgsMethod)... // -// // …expands to: -// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)… +// // ...expands to: +// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)... // |-----------------------v--------------------------| // invokes second overload // -// // …which is essentially: -// mock.gmock_TwoArgsMethod(_, _)… +// // ...which is essentially: +// mock.gmock_TwoArgsMethod(_, _)... // // The WithoutMatchers() argument is used to disambiguate overloads and to // block the caller from accidentally invoking the second overload directly. The diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index 4751788..c5841ab 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -348,7 +348,7 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message, // correct overload. This must not be instantiable, to prevent client code from // accidentally resolving to the overload; for example: // -// ON_CALL(mock, Method({}, nullptr))… +// ON_CALL(mock, Method({}, nullptr))... // class WithoutMatchers { private: -- cgit v0.12 From a091b753325322d329dc89262bfe5ad0ab20f1bf Mon Sep 17 00:00:00 2001 From: Syohei YOSHIDA Date: Tue, 17 Jul 2018 18:39:29 +0900 Subject: Ignore .DS_Store file --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index b294d3b..16c56e6 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,6 @@ googletest/m4/lt~obsolete.m4 # Ignore generated directories. googlemock/fused-src/ googletest/fused-src/ + +# macOS files +.DS_Store -- cgit v0.12 From 5437926b2213b1c45c2f34bd858734de90e5fffd Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Tue, 17 Jul 2018 17:47:25 -0400 Subject: Docs sync --- googletest/docs/advanced.md | 2546 ++++++++++++++++++++++--------------------- googletest/docs/faq.md | 1081 +++++++----------- googletest/docs/primer.md | 4 + 3 files changed, 1716 insertions(+), 1915 deletions(-) diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index 73b7954..6883784 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -1,67 +1,77 @@ +# Advanced googletest Topics -Now that you have read [Primer](primer.md) and learned how to write tests -using Google Test, it's time to learn some new tricks. This document -will show you more assertions as well as how to construct complex -failure messages, propagate fatal failures, reuse and speed up your -test fixtures, and use various flags with your tests. +## Introduction -# More Assertions # +Now that you have read the [googletest Primer](primer) and learned how to write +tests using googletest, it's time to learn some new tricks. This document will +show you more assertions as well as how to construct complex failure messages, +propagate fatal failures, reuse and speed up your test fixtures, and use various +flags with your tests. + +## More Assertions This section covers some less frequently used, but still significant, assertions. -## Explicit Success and Failure ## +### Explicit Success and Failure -These three assertions do not actually test a value or expression. Instead, -they generate a success or failure directly. Like the macros that actually -perform a test, you may stream a custom failure message into them. +These three assertions do not actually test a value or expression. Instead, they +generate a success or failure directly. Like the macros that actually perform a +test, you may stream a custom failure message into them. -| `SUCCEED();` | -|:-------------| +```c++ +SUCCEED(); +``` -Generates a success. This does NOT make the overall test succeed. A test is +Generates a success. This does **NOT** make the overall test succeed. A test is considered successful only if none of its assertions fail during its execution. -Note: `SUCCEED()` is purely documentary and currently doesn't generate any -user-visible output. However, we may add `SUCCEED()` messages to Google Test's +NOTE: `SUCCEED()` is purely documentary and currently doesn't generate any +user-visible output. However, we may add `SUCCEED()` messages to googletest's output in the future. -| `FAIL();` | `ADD_FAILURE();` | `ADD_FAILURE_AT("`_file\_path_`", `_line\_number_`);` | -|:-----------|:-----------------|:------------------------------------------------------| +```c++ +FAIL(); +ADD_FAILURE(); +ADD_FAILURE_AT("file_path", line_number); +``` -`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` generate a nonfatal -failure. These are useful when control flow, rather than a Boolean expression, -determines the test's success or failure. For example, you might want to write -something like: +`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` +generate a nonfatal failure. These are useful when control flow, rather than a +Boolean expression, determines the test's success or failure. For example, you +might want to write something like: -``` +```c++ switch(expression) { - case 1: ... some checks ... - case 2: ... some other checks - ... - default: FAIL() << "We shouldn't get here."; + case 1: + ... some checks ... + case 2: + ... some other checks ... + default: + FAIL() << "We shouldn't get here."; } ``` -Note: you can only use `FAIL()` in functions that return `void`. See the [Assertion Placement section](#assertion-placement) for more information. +NOTE: you can only use `FAIL()` in functions that return `void`. See the +[Assertion Placement section](#assertion-placement) for more information. -_Availability_: Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -## Exception Assertions ## +### Exception Assertions -These are for verifying that a piece of code throws (or does not -throw) an exception of the given type: +These are for verifying that a piece of code throws (or does not throw) an +exception of the given type: -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_THROW(`_statement_, _exception\_type_`);` | `EXPECT_THROW(`_statement_, _exception\_type_`);` | _statement_ throws an exception of the given type | -| `ASSERT_ANY_THROW(`_statement_`);` | `EXPECT_ANY_THROW(`_statement_`);` | _statement_ throws an exception of any type | -| `ASSERT_NO_THROW(`_statement_`);` | `EXPECT_NO_THROW(`_statement_`);` | _statement_ doesn't throw any exception | +Fatal assertion | Nonfatal assertion | Verifies +------------------------------------------ | ------------------------------------------ | -------- +`ASSERT_THROW(statement, exception_type);` | `EXPECT_THROW(statement, exception_type);` | `statement` throws an exception of the given type +`ASSERT_ANY_THROW(statement);` | `EXPECT_ANY_THROW(statement);` | `statement` throws an exception of any type +`ASSERT_NO_THROW(statement);` | `EXPECT_NO_THROW(statement);` | `statement` doesn't throw any exception Examples: -``` +```c++ ASSERT_THROW(Foo(5), bar_exception); EXPECT_NO_THROW({ @@ -70,79 +80,96 @@ EXPECT_NO_THROW({ }); ``` -_Availability_: Linux, Windows, Mac; since version 1.1.0. +**Availability**: Linux, Windows, Mac; requires exceptions to be enabled in the +build environment (note that `google3` **disables** exceptions). -## Predicate Assertions for Better Error Messages ## +### Predicate Assertions for Better Error Messages -Even though Google Test has a rich set of assertions, they can never be -complete, as it's impossible (nor a good idea) to anticipate all the scenarios -a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` -to check a complex expression, for lack of a better macro. This has the problem -of not showing you the values of the parts of the expression, making it hard to +Even though googletest has a rich set of assertions, they can never be complete, +as it's impossible (nor a good idea) to anticipate all scenarios a user might +run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a +complex expression, for lack of a better macro. This has the problem of not +showing you the values of the parts of the expression, making it hard to understand what went wrong. As a workaround, some users choose to construct the failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this is awkward especially when the expression has side-effects or is expensive to evaluate. -Google Test gives you three different options to solve this problem: +googletest gives you three different options to solve this problem: -### Using an Existing Boolean Function ### +#### Using an Existing Boolean Function -If you already have a function or a functor that returns `bool` (or a type -that can be implicitly converted to `bool`), you can use it in a _predicate -assertion_ to get the function arguments printed for free: +If you already have a function or functor that returns `bool` (or a type that +can be implicitly converted to `bool`), you can use it in a *predicate +assertion* to get the function arguments printed for free: -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_PRED1(`_pred1, val1_`);` | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true | -| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` | _pred2(val1, val2)_ returns true | -| ... | ... | ... | +| Fatal assertion | Nonfatal assertion | Verifies | +| -------------------- | -------------------- | --------------------------- | +| `ASSERT_PRED1(pred1, | `EXPECT_PRED1(pred1, | `pred1(val1)` is true | +: val1);` : val1);` : : +| `ASSERT_PRED2(pred2, | `EXPECT_PRED2(pred2, | `pred2(val1, val2)` is true | +: val1, val2);` : val1, val2);` : : +| `...` | `...` | ... | -In the above, _predn_ is an _n_-ary predicate function or functor, where -_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds -if the predicate returns `true` when applied to the given arguments, and fails +In the above, `predn` is an `n`-ary predicate function or functor, where `val1`, +`val2`, ..., and `valn` are its arguments. The assertion succeeds if the +predicate returns `true` when applied to the given arguments, and fails otherwise. When the assertion fails, it prints the value of each argument. In either case, the arguments are evaluated exactly once. Here's an example. Given -``` +```c++ // Returns true iff m and n have no common divisors except 1. bool MutuallyPrime(int m, int n) { ... } + const int a = 3; const int b = 4; const int c = 10; ``` -the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the -assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message +the assertion + +```c++ + EXPECT_PRED2(MutuallyPrime, a, b); +``` + +will succeed, while the assertion + +```c++ + EXPECT_PRED2(MutuallyPrime, b, c); +``` -
-!MutuallyPrime(b, c) is false, where
-b is 4
-c is 10
-
+will fail with the message -**Notes:** +```none +MutuallyPrime(b, c) is false, where +b is 4 +c is 10 +``` - 1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this FAQ](faq.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert_predn-how-do-i-fix-it) for how to resolve it. - 1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know. +> NOTE: +> +> 1. If you see a compiler error "no matching function to call" when using +> `ASSERT_PRED*` or `EXPECT_PRED*`, please see +> [this](faq#OverloadedPredicate) for how to resolve it. +> 1. Currently we only provide predicate assertions of arity <= 5. If you need +> a higher-arity assertion, let [us](http://g/opensource-gtest) know. -_Availability_: Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -### Using a Function That Returns an AssertionResult ### +#### Using a Function That Returns an AssertionResult -While `EXPECT_PRED*()` and friends are handy for a quick job, the -syntax is not satisfactory: you have to use different macros for -different arities, and it feels more like Lisp than C++. The -`::testing::AssertionResult` class solves this problem. +While `EXPECT_PRED*()` and friends are handy for a quick job, the syntax is not +satisfactory: you have to use different macros for different arities, and it +feels more like Lisp than C++. The `::testing::AssertionResult` class solves +this problem. -An `AssertionResult` object represents the result of an assertion -(whether it's a success or a failure, and an associated message). You -can create an `AssertionResult` using one of these factory -functions: +An `AssertionResult` object represents the result of an assertion (whether it's +a success or a failure, and an associated message). You can create an +`AssertionResult` using one of these factory functions: -``` +```c++ namespace testing { // Returns an AssertionResult object to indicate that an assertion has @@ -156,26 +183,25 @@ AssertionResult AssertionFailure(); } ``` -You can then use the `<<` operator to stream messages to the -`AssertionResult` object. +You can then use the `<<` operator to stream messages to the `AssertionResult` +object. -To provide more readable messages in Boolean assertions -(e.g. `EXPECT_TRUE()`), write a predicate function that returns -`AssertionResult` instead of `bool`. For example, if you define -`IsEven()` as: +To provide more readable messages in Boolean assertions (e.g. `EXPECT_TRUE()`), +write a predicate function that returns `AssertionResult` instead of `bool`. For +example, if you define `IsEven()` as: -``` +```c++ ::testing::AssertionResult IsEven(int n) { if ((n % 2) == 0) - return ::testing::AssertionSuccess(); + return ::testing::AssertionSuccess(); else - return ::testing::AssertionFailure() << n << " is odd"; + return ::testing::AssertionFailure() << n << " is odd"; } ``` instead of: -``` +```c++ bool IsEven(int n) { return (n % 2) == 0; } @@ -183,77 +209,83 @@ bool IsEven(int n) { the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print: -
-Value of: IsEven(Fib(4))
-Actual: false (*3 is odd*)
-Expected: true
-
+```none +Value of: IsEven(Fib(4)) + Actual: false (3 is odd) +Expected: true +``` instead of a more opaque -
-Value of: IsEven(Fib(4))
-Actual: false
-Expected: true
-
+```none +Value of: IsEven(Fib(4)) + Actual: false +Expected: true +``` -If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` -as well, and are fine with making the predicate slower in the success -case, you can supply a success message: +If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` as well +(one third of Boolean assertions in the Google code base are negative ones), and +are fine with making the predicate slower in the success case, you can supply a +success message: -``` +```c++ ::testing::AssertionResult IsEven(int n) { if ((n % 2) == 0) - return ::testing::AssertionSuccess() << n << " is even"; + return ::testing::AssertionSuccess() << n << " is even"; else - return ::testing::AssertionFailure() << n << " is odd"; + return ::testing::AssertionFailure() << n << " is odd"; } ``` Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print -
-Value of: IsEven(Fib(6))
-Actual: true (8 is even)
-Expected: false
-
+```none + Value of: IsEven(Fib(6)) + Actual: true (8 is even) + Expected: false +``` -_Availability_: Linux, Windows, Mac; since version 1.4.1. +**Availability**: Linux, Windows, Mac. -### Using a Predicate-Formatter ### +#### Using a Predicate-Formatter If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and `(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your predicate do not support streaming to `ostream`, you can instead use the -following _predicate-formatter assertions_ to _fully_ customize how the -message is formatted: - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);` | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`);` | _pred\_format1(val1)_ is successful | -| `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful | -| `...` | `...` | `...` | +following *predicate-formatter assertions* to *fully* customize how the message +is formatted: -The difference between this and the previous two groups of macros is that instead of -a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_ -(_pred\_formatn_), which is a function or functor with the signature: +Fatal assertion | Nonfatal assertion | Verifies +------------------------------------------------ | ------------------------------------------------ | -------- +`ASSERT_PRED_FORMAT1(pred_format1, val1);` | `EXPECT_PRED_FORMAT1(pred_format1, val1);` | `pred_format1(val1)` is successful +`ASSERT_PRED_FORMAT2(pred_format2, val1, val2);` | `EXPECT_PRED_FORMAT2(pred_format2, val1, val2);` | `pred_format2(val1, val2)` is successful +`...` | `...` | ... -`::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);` +The difference between this and the previous group of macros is that instead of +a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a *predicate-formatter* +(`pred_formatn`), which is a function or functor with the signature: -where _val1_, _val2_, ..., and _valn_ are the values of the predicate -arguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding -expressions as they appear in the source code. The types `T1`, `T2`, ..., and -`Tn` can be either value types or reference types. For example, if an -argument has type `Foo`, you can declare it as either `Foo` or `const Foo&`, -whichever is appropriate. +```c++ +::testing::AssertionResult PredicateFormattern(const char* expr1, + const char* expr2, + ... + const char* exprn, + T1 val1, + T2 val2, + ... + Tn valn); +``` -A predicate-formatter returns a `::testing::AssertionResult` object to indicate -whether the assertion has succeeded or not. The only way to create such an -object is to call one of these factory functions: +where `val1`, `val2`, ..., and `valn` are the values of the predicate arguments, +and `expr1`, `expr2`, ..., and `exprn` are the corresponding expressions as they +appear in the source code. The types `T1`, `T2`, ..., and `Tn` can be either +value types or reference types. For example, if an argument has type `Foo`, you +can declare it as either `Foo` or `const Foo&`, whichever is appropriate. -As an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`: +As an example, let's improve the failure message in `MutuallyPrime()`, which was +used with `EXPECT_PRED2()`: -``` +```c++ // Returns the smallest prime common divisor of m and n, // or 1 when m and n are mutually prime. int SmallestPrimeCommonDivisor(int m, int n) { ... } @@ -263,167 +295,260 @@ int SmallestPrimeCommonDivisor(int m, int n) { ... } const char* n_expr, int m, int n) { - if (MutuallyPrime(m, n)) - return ::testing::AssertionSuccess(); + if (MutuallyPrime(m, n)) return ::testing::AssertionSuccess(); - return ::testing::AssertionFailure() - << m_expr << " and " << n_expr << " (" << m << " and " << n - << ") are not mutually prime, " << "as they have a common divisor " - << SmallestPrimeCommonDivisor(m, n); + return ::testing::AssertionFailure() << m_expr << " and " << n_expr + << " (" << m << " and " << n << ") are not mutually prime, " + << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n); } ``` With this predicate-formatter, we can use -``` -EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); +```c++ + EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); ``` to generate the message -
-b and c (4 and 10) are not mutually prime, as they have a common divisor 2.
-
+```none +b and c (4 and 10) are not mutually prime, as they have a common divisor 2. +``` -As you may have realized, many of the assertions we introduced earlier are -special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are +As you may have realized, many of the built-in assertions we introduced earlier +are special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`. -_Availability_: Linux, Windows, Mac. - +**Availability**: Linux, Windows, Mac. -## Floating-Point Comparison ## +### Floating-Point Comparison -Comparing floating-point numbers is tricky. Due to round-off errors, it is -very unlikely that two floating-points will match exactly. Therefore, -`ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points -can have a wide value range, no single fixed error bound works. It's better to -compare by a fixed relative error bound, except for values close to 0 due to -the loss of precision there. +Comparing floating-point numbers is tricky. Due to round-off errors, it is very +unlikely that two floating-points will match exactly. Therefore, `ASSERT_EQ` 's +naive comparison usually doesn't work. And since floating-points can have a wide +value range, no single fixed error bound works. It's better to compare by a +fixed relative error bound, except for values close to 0 due to the loss of +precision there. In general, for floating-point comparison to make sense, the user needs to carefully choose the error bound. If they don't want or care to, comparing in -terms of Units in the Last Place (ULPs) is a good default, and Google Test +terms of Units in the Last Place (ULPs) is a good default, and googletest provides assertions to do this. Full details about ULPs are quite long; if you want to learn more, see -[this article on float comparison](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). +[here](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). + +#### Floating-Point Macros -### Floating-Point Macros ### +| Fatal assertion | Nonfatal assertion | Verifies | +| ----------------------- | ----------------------- | ----------------------- | +| `ASSERT_FLOAT_EQ(val1, | `EXPECT_FLOAT_EQ(val1, | the two `float` values | +: val2);` : val2);` : are almost equal : +| `ASSERT_DOUBLE_EQ(val1, | `EXPECT_DOUBLE_EQ(val1, | the two `double` values | +: val2);` : val2);` : are almost equal : -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_FLOAT_EQ(`_val1, val2_`);` | `EXPECT_FLOAT_EQ(`_val1, val2_`);` | the two `float` values are almost equal | -| `ASSERT_DOUBLE_EQ(`_val1, val2_`);` | `EXPECT_DOUBLE_EQ(`_val1, val2_`);` | the two `double` values are almost equal | +By "almost equal" we mean the values are within 4 ULP's from each other. -By "almost equal", we mean the two values are within 4 ULP's from each -other. +NOTE: `CHECK_DOUBLE_EQ()` in `base/logging.h` uses a fixed absolute error bound, +so its result may differ from that of the googletest macros. That macro is +unsafe and has been deprecated. Please don't use it any more. The following assertions allow you to choose the acceptable error bound: -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_NEAR(`_val1, val2, abs\_error_`);` | `EXPECT_NEAR`_(val1, val2, abs\_error_`);` | the difference between _val1_ and _val2_ doesn't exceed the given absolute error | +| Fatal assertion | Nonfatal assertion | Verifies | +| ------------------ | ------------------------ | ------------------------- | +| `ASSERT_NEAR(val1, | `EXPECT_NEAR(val1, val2, | the difference between | +: val2, abs_error);` : abs_error);` : `val1` and `val2` doesn't : +: : : exceed the given absolute : +: : : error : -_Availability_: Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -### Floating-Point Predicate-Format Functions ### +#### Floating-Point Predicate-Format Functions -Some floating-point operations are useful, but not that often used. In order -to avoid an explosion of new macros, we provide them as predicate-format -functions that can be used in predicate assertion macros (e.g. -`EXPECT_PRED_FORMAT2`, etc). +Some floating-point operations are useful, but not that often used. In order to +avoid an explosion of new macros, we provide them as predicate-format functions +that can be used in predicate assertion macros (e.g. `EXPECT_PRED_FORMAT2`, +etc). -``` +```c++ EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2); EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2); ``` -Verifies that _val1_ is less than, or almost equal to, _val2_. You can -replace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`. +Verifies that `val1` is less than, or almost equal to, `val2`. You can replace +`EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`. -_Availability_: Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. + +### Asserting Using gMock Matchers + +Google-developed C++ mocking framework [gMock](http://go/gmock) comes with a +library of matchers for validating arguments passed to mock objects. A gMock +*matcher* is basically a predicate that knows how to describe itself. It can be +used in these assertion macros: + +| Fatal assertion | Nonfatal assertion | Verifies | +| ------------------- | ------------------------------ | --------------------- | +| `ASSERT_THAT(value, | `EXPECT_THAT(value, matcher);` | value matches matcher | +: matcher);` : : : -## Windows HRESULT assertions ## +For example, `StartsWith(prefix)` is a matcher that matches a string starting +with `prefix`, and you can write: + +```c++ +using ::testing::StartsWith; +... + // Verifies that Foo() returns a string starting with "Hello". + EXPECT_THAT(Foo(), StartsWith("Hello")); +``` + +Read this [recipe](http://go/gmockguide#using-matchers-in-gunit-assertions) in +the gMock Cookbook for more details. + +gMock has a rich set of matchers. You can do many things googletest cannot do +alone with them. For a list of matchers gMock provides, read +[this](http://go/gmockguide#using-matchers). Especially useful among them are +some [protocol buffer matchers](http://go/protomatchers). It's easy to write +your [own matchers](http://go/gmockguide#NewMatchers) too. + +For example, you can use gMock's +[EqualsProto](http://cs/#piper///depot/google3/testing/base/public/gmock_utils/protocol-buffer-matchers.h) +to compare protos in your tests: + +```c++ +#include "testing/base/public/gmock.h" +using ::testing::EqualsProto; +... + EXPECT_THAT(actual_proto, EqualsProto("foo: 123 bar: 'xyz'")); + EXPECT_THAT(*actual_proto_ptr, EqualsProto(expected_proto)); +``` + +gMock is bundled with googletest, so you don't need to add any build dependency +in order to take advantage of this. Just include `"testing/base/public/gmock.h"` +and you're ready to go. + +**Availability**: Linux, Windows, and Mac. + +### More String Assertions + +(Please read the [previous](#AssertThat) section first if you haven't.) + +You can use the gMock [string matchers](http://go/gmockguide#string-matchers) +with `EXPECT_THAT()` or `ASSERT_THAT()` to do more string comparison tricks +(sub-string, prefix, suffix, regular expression, and etc). For example, + +```c++ +using ::testing::HasSubstr; +using ::testing::MatchesRegex; +... + ASSERT_THAT(foo_string, HasSubstr("needle")); + EXPECT_THAT(bar_string, MatchesRegex("\\w*\\d+")); +``` + +**Availability**: Linux, Windows, Mac. + +If the string contains a well-formed HTML or XML document, you can check whether +its DOM tree matches an [XPath +expression](http://www.w3.org/TR/xpath/#contents): + +```c++ +// Currently still in //template/prototemplate/testing:xpath_matcher +#include "template/prototemplate/testing/xpath_matcher.h" +using prototemplate::testing::MatchesXPath; +EXPECT_THAT(html_string, MatchesXPath("//a[text()='click here']")); +``` + +**Availability**: Linux. + +### Windows HRESULT assertions These assertions test for `HRESULT` success or failure. -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` | -| `ASSERT_HRESULT_FAILED(`_expression_`);` | `EXPECT_HRESULT_FAILED(`_expression_`);` | _expression_ is a failure `HRESULT` | +Fatal assertion | Nonfatal assertion | Verifies +-------------------------------------- | -------------------------------------- | -------- +`ASSERT_HRESULT_SUCCEEDED(expression)` | `EXPECT_HRESULT_SUCCEEDED(expression)` | `expression` is a success `HRESULT` +`ASSERT_HRESULT_FAILED(expression)` | `EXPECT_HRESULT_FAILED(expression)` | `expression` is a failure `HRESULT` -The generated output contains the human-readable error message -associated with the `HRESULT` code returned by _expression_. +The generated output contains the human-readable error message associated with +the `HRESULT` code returned by `expression`. You might use them like this: -``` -CComPtr shell; +```c++ +CComPtr shell; ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application")); CComVariant empty; ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); ``` -_Availability_: Windows. +**Availability**: Windows. -## Type Assertions ## +### Type Assertions You can call the function -``` + +```c++ ::testing::StaticAssertTypeEq(); ``` -to assert that types `T1` and `T2` are the same. The function does -nothing if the assertion is satisfied. If the types are different, -the function call will fail to compile, and the compiler error message -will likely (depending on the compiler) show you the actual values of -`T1` and `T2`. This is mainly useful inside template code. -_Caveat:_ When used inside a member function of a class template or a -function template, `StaticAssertTypeEq()` is effective _only if_ -the function is instantiated. For example, given: -``` +to assert that types `T1` and `T2` are the same. The function does nothing if +the assertion is satisfied. If the types are different, the function call will +fail to compile, and the compiler error message will likely (depending on the +compiler) show you the actual values of `T1` and `T2`. This is mainly useful +inside template code. + +**Caveat**: When used inside a member function of a class template or a function +template, `StaticAssertTypeEq()` is effective only if the function is +instantiated. For example, given: + +```c++ template class Foo { public: void Bar() { ::testing::StaticAssertTypeEq(); } }; ``` + the code: -``` + +```c++ void Test1() { Foo foo; } ``` -will _not_ generate a compiler error, as `Foo::Bar()` is never -actually instantiated. Instead, you need: -``` + +will not generate a compiler error, as `Foo::Bar()` is never actually +instantiated. Instead, you need: + +```c++ void Test2() { Foo foo; foo.Bar(); } ``` + to cause a compiler error. -_Availability:_ Linux, Windows, Mac; since version 1.3.0. +**Availability**: Linux, Windows, Mac. -## Assertion Placement ## +### Assertion Placement -You can use assertions in any C++ function. In particular, it doesn't -have to be a method of the test fixture class. The one constraint is -that assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`) -can only be used in void-returning functions. This is a consequence of -Google Test not using exceptions. By placing it in a non-void function -you'll get a confusing compile error like -`"error: void value not ignored as it ought to be"`. +You can use assertions in any C++ function. In particular, it doesn't have to be +a method of the test fixture class. The one constraint is that assertions that +generate a fatal failure (`FAIL*` and `ASSERT_*`) can only be used in +void-returning functions. This is a consequence of Google's not using +exceptions. By placing it in a non-void function you'll get a confusing compile +error like `"error: void value not ignored as it ought to be"` or `"cannot +initialize return object of type 'bool' with an rvalue of type 'void'"` or +`"error: no viable conversion from 'void' to 'string'"`. -If you need to use assertions in a function that returns non-void, one option -is to make the function return the value in an out parameter instead. For +If you need to use fatal assertions in a function that returns non-void, one +option is to make the function return the value in an out parameter instead. For example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You need to make sure that `*result` contains some sensible value even when the function returns prematurely. As the function now returns `void`, you can use any assertion inside of it. -If changing the function's type is not an option, you should just use -assertions that generate non-fatal failures, such as `ADD_FAILURE*` and -`EXPECT_*`. +If changing the function's type is not an option, you should just use assertions +that generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`. -_Note_: Constructors and destructors are not considered void-returning -functions, according to the C++ language specification, and so you may not use -fatal assertions in them. You'll get a compilation error if you try. A simple +NOTE: Constructors and destructors are not considered void-returning functions, +according to the C++ language specification, and so you may not use fatal +assertions in them. You'll get a compilation error if you try. A simple workaround is to transfer the entire body of the constructor or destructor to a private void-returning method. However, you should be aware that a fatal assertion failure in a constructor does not terminate the current test, as your @@ -432,30 +557,37 @@ leaving your object in a partially-constructed state. Likewise, a fatal assertion failure in a destructor may leave your object in a partially-destructed state. Use assertions carefully in these situations! -# Teaching Google Test How to Print Your Values # +## Teaching googletest How to Print Your Values -When a test assertion such as `EXPECT_EQ` fails, Google Test prints the -argument values to help you debug. It does this using a -user-extensible value printer. +When a test assertion such as `EXPECT_EQ` fails, googletest prints the argument +values to help you debug. It does this using a user-extensible value printer. This printer knows how to print built-in C++ types, native arrays, STL -containers, and any type that supports the `<<` operator. For other -types, it prints the raw bytes in the value and hopes that you the -user can figure it out. +containers, and any type that supports the `<<` operator. For other types, it +prints the raw bytes in the value and hopes that you the user can figure it out. -As mentioned earlier, the printer is _extensible_. That means -you can teach it to do a better job at printing your particular type -than to dump the bytes. To do that, define `<<` for your type: +As mentioned earlier, the printer is *extensible*. That means you can teach it +to do a better job at printing your particular type than to dump the bytes. To +do that, define `<<` for your type: -``` -#include +```c++ +// Streams are allowed only for logging. Don't include this for +// any other purpose. +#include namespace foo { -class Bar { ... }; // We want Google Test to be able to print instances of this. +class Bar { // We want googletest to be able to print instances of this. +... + // Create a free inline friend function. + friend ::std::ostream& operator<<(::std::ostream& os, const Bar& bar) { + return os << bar.DebugString(); // whatever needed to print bar to os + } +}; -// It's important that the << operator is defined in the SAME -// namespace that defines Bar. C++'s look-up rules rely on that. +// If you can't declare the function in the class it's important that the +// << operator is defined in the SAME namespace that defines Bar. C++'s look-up +// rules rely on that. ::std::ostream& operator<<(::std::ostream& os, const Bar& bar) { return os << bar.DebugString(); // whatever needed to print bar to os } @@ -463,20 +595,28 @@ class Bar { ... }; // We want Google Test to be able to print instances of this } // namespace foo ``` -Sometimes, this might not be an option: your team may consider it bad -style to have a `<<` operator for `Bar`, or `Bar` may already have a -`<<` operator that doesn't do what you want (and you cannot change -it). If so, you can instead define a `PrintTo()` function like this: +Sometimes, this might not be an option: your team may consider it bad style to +have a `<<` operator for `Bar`, or `Bar` may already have a `<<` operator that +doesn't do what you want (and you cannot change it). If so, you can instead +define a `PrintTo()` function like this: -``` -#include +```c++ +// Streams are allowed only for logging. Don't include this for +// any other purpose. +#include namespace foo { -class Bar { ... }; +class Bar { + ... + friend void PrintTo(const Bar& bar, ::std::ostream* os) { + *os << bar.DebugString(); // whatever needed to print bar to os + } +}; -// It's important that PrintTo() is defined in the SAME -// namespace that defines Bar. C++'s look-up rules rely on that. +// If you can't declare the function in the class it's important that PrintTo() +// is defined in the SAME namespace that defines Bar. C++'s look-up rules rely +// on that. void PrintTo(const Bar& bar, ::std::ostream* os) { *os << bar.DebugString(); // whatever needed to print bar to os } @@ -484,85 +624,86 @@ void PrintTo(const Bar& bar, ::std::ostream* os) { } // namespace foo ``` -If you have defined both `<<` and `PrintTo()`, the latter will be used -when Google Test is concerned. This allows you to customize how the value -appears in Google Test's output without affecting code that relies on the -behavior of its `<<` operator. +If you have defined both `<<` and `PrintTo()`, the latter will be used when +googletest is concerned. This allows you to customize how the value appears in +googletest's output without affecting code that relies on the behavior of its +`<<` operator. -If you want to print a value `x` using Google Test's value printer -yourself, just call `::testing::PrintToString(`_x_`)`, which -returns an `std::string`: +If you want to print a value `x` using googletest's value printer yourself, just +call `::testing::PrintToString(x)`, which returns an `std::string`: -``` +```c++ vector > bar_ints = GetBarIntVector(); EXPECT_TRUE(IsCorrectBarIntVector(bar_ints)) << "bar_ints = " << ::testing::PrintToString(bar_ints); ``` -# Death Tests # +## Death Tests -In many applications, there are assertions that can cause application failure -if a condition is not met. These sanity checks, which ensure that the program -is in a known good state, are there to fail at the earliest possible time after -some program state is corrupted. If the assertion checks the wrong condition, -then the program may proceed in an erroneous state, which could lead to memory -corruption, security holes, or worse. Hence it is vitally important to test -that such assertion statements work as expected. +In many applications, there are assertions that can cause application failure if +a condition is not met. These sanity checks, which ensure that the program is in +a known good state, are there to fail at the earliest possible time after some +program state is corrupted. If the assertion checks the wrong condition, then +the program may proceed in an erroneous state, which could lead to memory +corruption, security holes, or worse. Hence it is vitally important to test that +such assertion statements work as expected. Since these precondition checks cause the processes to die, we call such tests _death tests_. More generally, any test that checks that a program terminates (except by throwing an exception) in an expected fashion is also a death test. + Note that if a piece of code throws an exception, we don't consider it "death" -for the purpose of death tests, as the caller of the code could catch the exception -and avoid the crash. If you want to verify exceptions thrown by your code, -see [Exception Assertions](#exception-assertions). +for the purpose of death tests, as the caller of the code could catch the +exception and avoid the crash. If you want to verify exceptions thrown by your +code, see [Exception Assertions](#ExceptionAssertions). -If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#catching-failures). +If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see +Catching Failures -## How to Write a Death Test ## +### How to Write a Death Test -Google Test has the following macros to support death tests: +googletest has the following macros to support death tests: -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_DEATH(`_statement, regex_`);` | `EXPECT_DEATH(`_statement, regex_`);` | _statement_ crashes with the given error | -| `ASSERT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | `EXPECT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | if death tests are supported, verifies that _statement_ crashes with the given error; otherwise verifies nothing | -| `ASSERT_EXIT(`_statement, predicate, regex_`);` | `EXPECT_EXIT(`_statement, predicate, regex_`);` |_statement_ exits with the given error and its exit code matches _predicate_ | +Fatal assertion | Nonfatal assertion | Verifies +---------------------------------------------- | ---------------------------------------------- | -------- +`ASSERT_DEATH(statement, regex);` | `EXPECT_DEATH(statement, regex);` | `statement` crashes with the given error +`ASSERT_DEATH_IF_SUPPORTED(statement, regex);` | `EXPECT_DEATH_IF_SUPPORTED(statement, regex);` | if death tests are supported, verifies that `statement` crashes with the given error; otherwise verifies nothing +`ASSERT_EXIT(statement, predicate, regex);` | `EXPECT_EXIT(statement, predicate, regex);` | `statement` exits with the given error, and its exit code matches `predicate` -where _statement_ is a statement that is expected to cause the process to -die, _predicate_ is a function or function object that evaluates an integer -exit status, and _regex_ is a regular expression that the stderr output of -_statement_ is expected to match. Note that _statement_ can be _any valid -statement_ (including _compound statement_) and doesn't have to be an +where `statement` is a statement that is expected to cause the process to die, +`predicate` is a function or function object that evaluates an integer exit +status, and `regex` is a (Perl) regular expression that the stderr output of +`statement` is expected to match. Note that `statement` can be *any valid +statement* (including *compound statement*) and doesn't have to be an expression. + As usual, the `ASSERT` variants abort the current test function, while the `EXPECT` variants do not. -**Note:** We use the word "crash" here to mean that the process -terminates with a _non-zero_ exit status code. There are two -possibilities: either the process has called `exit()` or `_exit()` -with a non-zero value, or it may be killed by a signal. - -This means that if _statement_ terminates the process with a 0 exit -code, it is _not_ considered a crash by `EXPECT_DEATH`. Use -`EXPECT_EXIT` instead if this is the case, or if you want to restrict -the exit code more precisely. +> NOTE: We use the word "crash" here to mean that the process terminates with a +> *non-zero* exit status code. There are two possibilities: either the process +> has called `exit()` or `_exit()` with a non-zero value, or it may be killed by +> a signal. +> +> This means that if `*statement*` terminates the process with a 0 exit code, it +> is *not* considered a crash by `EXPECT_DEATH`. Use `EXPECT_EXIT` instead if +> this is the case, or if you want to restrict the exit code more precisely. A predicate here must accept an `int` and return a `bool`. The death test -succeeds only if the predicate returns `true`. Google Test defines a few +succeeds only if the predicate returns `true`. googletest defines a few predicates that handle the most common cases: -``` +```c++ ::testing::ExitedWithCode(exit_code) ``` This expression is `true` if the program exited normally with the given exit code. -``` +```c++ ::testing::KilledBySignal(signal_number) // Not available on Windows. ``` @@ -573,49 +714,63 @@ that verifies the process' exit code is non-zero. Note that a death test only cares about three things: - 1. does _statement_ abort or exit the process? - 1. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy _predicate_? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero? And - 1. does the stderr output match _regex_? +1. does `statement` abort or exit the process? +2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status + satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) + is the exit status non-zero? And +3. does the stderr output match `regex`? -In particular, if _statement_ generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as Google Test assertions don't abort the process. +In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it +will **not** cause the death test to fail, as googletest assertions don't abort +the process. To write a death test, simply use one of the above macros inside your test function. For example, -``` +```c++ TEST(MyDeathTest, Foo) { // This death test uses a compound statement. - ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()"); + ASSERT_DEATH({ + int n = 5; + Foo(&n); + }, "Error on line .* of Foo()"); } + TEST(MyDeathTest, NormalExit) { EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success"); } + TEST(MyDeathTest, KillMyself) { - EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal"); + EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), + "Sending myself unblockable signal"); } ``` verifies that: - * calling `Foo(5)` causes the process to die with the given error message, - * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and - * calling `KillMyself()` kills the process with signal `SIGKILL`. +* calling `Foo(5)` causes the process to die with the given error message, +* calling `NormalExit()` causes the process to print `"Success"` to stderr and + exit with exit code 0, and +* calling `KillMyself()` kills the process with signal `SIGKILL`. The test function body may contain other assertions and statements as well, if necessary. -_Important:_ We strongly recommend you to follow the convention of naming your -test case (not test) `*DeathTest` when it contains a death test, as -demonstrated in the above example. The `Death Tests And Threads` section below -explains why. +### Death Test Naming -If a test fixture class is shared by normal tests and death tests, you -can use typedef to introduce an alias for the fixture class and avoid +IMPORTANT: We strongly recommend you to follow the convention of naming your +**test case** (not test) `*DeathTest` when it contains a death test, as +demonstrated in the above example. The [Death Tests And +Threads](#death-tests-and-threads) section below explains why. + +If a test fixture class is shared by normal tests and death tests, you can use +`using` or `typedef` to introduce an alias for the fixture class and avoid duplicating its code: -``` + +```c++ class FooTest : public ::testing::Test { ... }; -typedef FooTest FooDeathTest; +using FooDeathTest = FooTest; TEST_F(FooTest, DoesThis) { // normal test @@ -626,79 +781,86 @@ TEST_F(FooDeathTest, DoesThat) { } ``` -_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac (the latter three are supported since v1.3.0). `(ASSERT|EXPECT)_DEATH_IF_SUPPORTED` are new in v1.4.0. +**Availability**: Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac + +### Regular Expression Syntax -## Regular Expression Syntax ## -On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the +On POSIX systems (e.g. Linux, Cygwin, and Mac), googletest uses the [POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) -syntax in death tests. To learn about this syntax, you may want to read this [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). - -On Windows, Google Test uses its own simple regular expression -implementation. It lacks many features you can find in POSIX extended -regular expressions. For example, we don't support union (`"x|y"`), -grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count -(`"x{5,7}"`), among others. Below is what we do support (Letter `A` denotes a -literal character, period (`.`), or a single `\\` escape sequence; `x` -and `y` denote regular expressions.): - -| `c` | matches any literal character `c` | -|:----|:----------------------------------| -| `\\d` | matches any decimal digit | -| `\\D` | matches any character that's not a decimal digit | -| `\\f` | matches `\f` | -| `\\n` | matches `\n` | -| `\\r` | matches `\r` | -| `\\s` | matches any ASCII whitespace, including `\n` | -| `\\S` | matches any character that's not a whitespace | -| `\\t` | matches `\t` | -| `\\v` | matches `\v` | -| `\\w` | matches any letter, `_`, or decimal digit | -| `\\W` | matches any character that `\\w` doesn't match | -| `\\c` | matches any literal character `c`, which must be a punctuation | -| `\\.` | matches the `.` character | -| `.` | matches any single character except `\n` | -| `A?` | matches 0 or 1 occurrences of `A` | -| `A*` | matches 0 or many occurrences of `A` | -| `A+` | matches 1 or many occurrences of `A` | -| `^` | matches the beginning of a string (not that of each line) | -| `$` | matches the end of a string (not that of each line) | -| `xy` | matches `x` followed by `y` | - -To help you determine which capability is available on your system, -Google Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX -extended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when it uses -the simple version. If you want your death tests to work in both -cases, you can either `#if` on these macros or use the more limited -syntax only. - -## How It Works ## - -Under the hood, `ASSERT_EXIT()` spawns a new process and executes the -death test statement in that process. The details of how precisely -that happens depend on the platform and the variable -`::testing::GTEST_FLAG(death_test_style)` (which is initialized from the -command-line flag `--gtest_death_test_style`). - - * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the child, after which: - * If the variable's value is `"fast"`, the death test statement is immediately executed. - * If the variable's value is `"threadsafe"`, the child process re-executes the unit test binary just as it was originally invoked, but with some extra flags to cause just the single death test under consideration to be run. - * On Windows, the child is spawned using the `CreateProcess()` API, and re-executes the binary to cause just the single death test under consideration to be run - much like the `threadsafe` mode on POSIX. - -Other values for the variable are illegal and will cause the death test to -fail. Currently, the flag's default value is `"fast"`. However, we reserve the -right to change it in the future. Therefore, your tests should not depend on -this. - -In either case, the parent process waits for the child process to complete, and checks that - - 1. the child's exit status satisfies the predicate, and - 1. the child's stderr matches the regular expression. - -If the death test statement runs to completion without dying, the child -process will nonetheless terminate, and the assertion fails. - -## Death Tests And Threads ## +syntax. To learn about this syntax, you may want to read this +[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). + +On Windows, googletest uses its own simple regular expression implementation. It +lacks many features. For example, we don't support union (`"x|y"`), grouping +(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among +others. Below is what we do support (`A` denotes a literal character, period +(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular +expressions.): + +Expression | Meaning +---------- | -------------------------------------------------------------- +`c` | matches any literal character `c` +`\\d` | matches any decimal digit +`\\D` | matches any character that's not a decimal digit +`\\f` | matches `\f` +`\\n` | matches `\n` +`\\r` | matches `\r` +`\\s` | matches any ASCII whitespace, including `\n` +`\\S` | matches any character that's not a whitespace +`\\t` | matches `\t` +`\\v` | matches `\v` +`\\w` | matches any letter, `_`, or decimal digit +`\\W` | matches any character that `\\w` doesn't match +`\\c` | matches any literal character `c`, which must be a punctuation +`.` | matches any single character except `\n` +`A?` | matches 0 or 1 occurrences of `A` +`A*` | matches 0 or many occurrences of `A` +`A+` | matches 1 or many occurrences of `A` +`^` | matches the beginning of a string (not that of each line) +`$` | matches the end of a string (not that of each line) +`xy` | matches `x` followed by `y` + +To help you determine which capability is available on your system, googletest +defines macros to govern which regular expression it is using. The macros are: +`GTEST_USES_PCRE=1`, or + `GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If +you want your death tests to work in all cases, you can either `#if` on these +macros or use the more limited syntax only. + +### How It Works + +Under the hood, `ASSERT_EXIT()` spawns a new process and executes the death test +statement in that process. The details of how precisely that happens depend on +the platform and the variable ::testing::GTEST_FLAG(death_test_style) (which is +initialized from the command-line flag `--gtest_death_test_style`). + +* On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the + child, after which: + * If the variable's value is `"fast"`, the death test statement is + immediately executed. + * If the variable's value is `"threadsafe"`, the child process re-executes + the unit test binary just as it was originally invoked, but with some + extra flags to cause just the single death test under consideration to + be run. +* On Windows, the child is spawned using the `CreateProcess()` API, and + re-executes the binary to cause just the single death test under + consideration to be run - much like the `threadsafe` mode on POSIX. + +Other values for the variable are illegal and will cause the death test to fail. +Currently, the flag's default value is +"fast". However, we reserve +the right to change it in the future. Therefore, your tests should not depend on +this. In either case, the parent process waits for the child process to +complete, and checks that + +1. the child's exit status satisfies the predicate, and +2. the child's stderr matches the regular expression. + +If the death test statement runs to completion without dying, the child process +will nonetheless terminate, and the assertion fails. + +### Death Tests And Threads The reason for the two death test styles has to do with thread safety. Due to well-known problems with forking in the presence of threads, death tests should @@ -707,35 +869,43 @@ arrange that kind of environment. For example, statically-initialized modules may start threads before main is ever reached. Once threads have been created, it may be difficult or impossible to clean them up. -Google Test has three features intended to raise awareness of threading issues. +googletest has three features intended to raise awareness of threading issues. - 1. A warning is emitted if multiple threads are running when a death test is encountered. - 1. Test cases with a name ending in "DeathTest" are run before all other tests. - 1. It uses `clone()` instead of `fork()` to spawn the child process on Linux (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely to cause the child to hang when the parent process has multiple threads. +1. A warning is emitted if multiple threads are running when a death test is + encountered. +2. Test cases with a name ending in "DeathTest" are run before all other tests. +3. It uses `clone()` instead of `fork()` to spawn the child process on Linux + (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely + to cause the child to hang when the parent process has multiple threads. It's perfectly fine to create threads inside a death test statement; they are executed in a separate process and cannot affect the parent. -## Death Test Styles ## +### Death Test Styles + The "threadsafe" death test style was introduced in order to help mitigate the risks of testing in a possibly multithreaded environment. It trades increased test execution time (potentially dramatically so) for improved thread safety. -We suggest using the faster, default "fast" style unless your test has specific -problems with it. -You can choose a particular style of death tests by setting the flag -programmatically: +The automated testing framework does not set the style flag. You can choose a +particular style of death tests by setting the flag programmatically: -``` -::testing::FLAGS_gtest_death_test_style = "threadsafe"; +```c++ +testing::FLAGS_gtest_death_test_style="threadsafe" ``` -You can do this in `main()` to set the style for all death tests in the -binary, or in individual tests. Recall that flags are saved before running each -test and restored afterwards, so you need not do that yourself. For example: +You can do this in `main()` to set the style for all death tests in the binary, +or in individual tests. Recall that flags are saved before running each test and +restored afterwards, so you need not do that yourself. For example: + +```c++ +int main(int argc, char** argv) { + InitGoogle(argv[0], &argc, &argv, true); + ::testing::FLAGS_gtest_death_test_style = "fast"; + return RUN_ALL_TESTS(); +} -``` TEST(MyDeathTest, TestOne) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; // This test is run in the "threadsafe" style: @@ -746,52 +916,51 @@ TEST(MyDeathTest, TestTwo) { // This test is run in the "fast" style: ASSERT_DEATH(ThisShouldDie(), ""); } - -int main(int argc, char** argv) { - ::testing::InitGoogleTest(&argc, argv); - ::testing::FLAGS_gtest_death_test_style = "fast"; - return RUN_ALL_TESTS(); -} ``` -## Caveats ## -The _statement_ argument of `ASSERT_EXIT()` can be any valid C++ statement. -If it leaves the current function via a `return` statement or by throwing an exception, -the death test is considered to have failed. Some Google Test macros may return -from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid them in _statement_. +### Caveats -Since _statement_ runs in the child process, any in-memory side effect (e.g. -modifying a variable, releasing memory, etc) it causes will _not_ be observable +The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If +it leaves the current function via a `return` statement or by throwing an +exception, the death test is considered to have failed. Some googletest macros +may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid +them in `statement`. + +Since `statement` runs in the child process, any in-memory side effect (e.g. +modifying a variable, releasing memory, etc) it causes will *not* be observable in the parent process. In particular, if you release memory in a death test, your program will fail the heap check as the parent process will never see the memory reclaimed. To solve this problem, you can - 1. try not to free memory in a death test; - 1. free the memory again in the parent process; or - 1. do not use the heap checker in your program. +1. try not to free memory in a death test; +2. free the memory again in the parent process; or +3. do not use the heap checker in your program. -Due to an implementation detail, you cannot place multiple death test -assertions on the same line; otherwise, compilation will fail with an unobvious -error message. +Due to an implementation detail, you cannot place multiple death test assertions +on the same line; otherwise, compilation will fail with an unobvious error +message. Despite the improved thread safety afforded by the "threadsafe" style of death test, thread problems such as deadlock are still possible in the presence of handlers registered with `pthread_atfork(3)`. -# Using Assertions in Sub-routines # -## Adding Traces to Assertions ## +## Using Assertions in Sub-routines + +### Adding Traces to Assertions -If a test sub-routine is called from several places, when an assertion -inside it fails, it can be hard to tell which invocation of the -sub-routine the failure is from. You can alleviate this problem using -extra logging or custom failure messages, but that usually clutters up -your tests. A better solution is to use the `SCOPED_TRACE` macro or -the `ScopedTrace` utility: +If a test sub-routine is called from several places, when an assertion inside it +fails, it can be hard to tell which invocation of the sub-routine the failure is +from. +You can alleviate this problem using extra logging or custom failure messages, +but that usually clutters up your tests. A better solution is to use the +`SCOPED_TRACE` macro or the `ScopedTrace` utility: -| `SCOPED_TRACE(`_message_`);` | `::testing::ScopedTrace trace(`_"file\_path"_`, `_line\_number_`, `_message_`);` | -|:-----------------------------|:---------------------------------------------------------------------------------| +```c++ +SCOPED_TRACE(message); +ScopedTrace trace("file_path", line_number, message); +``` where `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE` macro will cause the current file name, line number, and the given message to be @@ -801,7 +970,7 @@ will be undone when the control leaves the current lexical scope. For example, -``` +```c++ 10: void Sub1(int n) { 11: EXPECT_EQ(1, Bar(n)); 12: EXPECT_EQ(2, Bar(n + 1)); @@ -820,7 +989,7 @@ For example, could result in messages like these: -``` +```none path/to/foo_test.cc:11: Failure Value of: Bar(n) Expected: 1 @@ -834,45 +1003,56 @@ Expected: 2 Actual: 3 ``` -Without the trace, it would've been difficult to know which invocation -of `Sub1()` the two failures come from respectively. (You could add an -extra message to each assertion in `Sub1()` to indicate the value of -`n`, but that's tedious.) +Without the trace, it would've been difficult to know which invocation of +`Sub1()` the two failures come from respectively. (You could add + +an extra message to each assertion in `Sub1()` to indicate the value of `n`, but +that's tedious.) Some tips on using `SCOPED_TRACE`: - 1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the beginning of a sub-routine, instead of at each call site. - 1. When calling sub-routines inside a loop, make the loop iterator part of the message in `SCOPED_TRACE` such that you can know which iteration the failure is from. - 1. Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for `SCOPED_TRACE`. You can simply use `""`. - 1. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered. - 1. The trace dump is clickable in Emacs' compilation buffer - hit return on a line number and you'll be taken to that line in the source file! +1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the + beginning of a sub-routine, instead of at each call site. +2. When calling sub-routines inside a loop, make the loop iterator part of the + message in `SCOPED_TRACE` such that you can know which iteration the failure + is from. +3. Sometimes the line number of the trace point is enough for identifying the + particular invocation of a sub-routine. In this case, you don't have to + choose a unique message for `SCOPED_TRACE`. You can simply use `""`. +4. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer + scope. In this case, all active trace points will be included in the failure + messages, in reverse order they are encountered. +5. The trace dump is clickable in Emacs - hit `return` on a line number and + you'll be taken to that line in the source file! -_Availability:_ Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -## Propagating Fatal Failures ## +### Propagating Fatal Failures A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that when they fail they only abort the _current function_, not the entire test. For example, the following test will segfault: -``` + +```c++ void Subroutine() { // Generates a fatal failure and aborts the current function. ASSERT_EQ(1, 2); + // The following won't be executed. ... } TEST(FooTest, Bar) { - Subroutine(); - // The intended behavior is for the fatal failure - // in Subroutine() to abort the entire test. + Subroutine(); // The intended behavior is for the fatal failure + // in Subroutine() to abort the entire test. + // The actual behavior: the function goes on after Subroutine() returns. int* p = NULL; - *p = 3; // Segfault! + *p = 3; // Segfault! } ``` -To alleviate this, gUnit provides three different solutions. You could use +To alleviate this, googletest provides three different solutions. You could use either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the `HasFatalFailure()` function. They are described in the following two subsections. @@ -899,26 +1079,26 @@ int main(int argc, char** argv) { This listener should be added after other listeners if you have any, otherwise they won't see failed `OnTestPartResult`. -### Asserting on Subroutines ### +#### Asserting on Subroutines -As shown above, if your test calls a subroutine that has an `ASSERT_*` -failure in it, the test will continue after the subroutine -returns. This may not be what you want. +As shown above, if your test calls a subroutine that has an `ASSERT_*` failure +in it, the test will continue after the subroutine returns. This may not be what +you want. -Often people want fatal failures to propagate like exceptions. For -that Google Test offers the following macros: +Often people want fatal failures to propagate like exceptions. For that +googletest offers the following macros: -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_NO_FATAL_FAILURE(`_statement_`);` | `EXPECT_NO_FATAL_FAILURE(`_statement_`);` | _statement_ doesn't generate any new fatal failures in the current thread. | +Fatal assertion | Nonfatal assertion | Verifies +------------------------------------- | ------------------------------------- | -------- +`ASSERT_NO_FATAL_FAILURE(statement);` | `EXPECT_NO_FATAL_FAILURE(statement);` | `statement` doesn't generate any new fatal failures in the current thread. -Only failures in the thread that executes the assertion are checked to -determine the result of this type of assertions. If _statement_ -creates new threads, failures in these threads are ignored. +Only failures in the thread that executes the assertion are checked to determine +the result of this type of assertions. If `statement` creates new threads, +failures in these threads are ignored. Examples: -``` +```c++ ASSERT_NO_FATAL_FAILURE(Foo()); int i; @@ -927,17 +1107,16 @@ EXPECT_NO_FATAL_FAILURE({ }); ``` -_Availability:_ Linux, Windows, Mac. Assertions from multiple threads -are currently not supported. +**Availability**: Linux, Windows, Mac. Assertions from multiple threads are +currently not supported on Windows. -### Checking for Failures in the Current Test ### +#### Checking for Failures in the Current Test `HasFatalFailure()` in the `::testing::Test` class returns `true` if an -assertion in the current test has suffered a fatal failure. This -allows functions to catch fatal failures in a sub-routine and return -early. +assertion in the current test has suffered a fatal failure. This allows +functions to catch fatal failures in a sub-routine and return early. -``` +```c++ class Test { public: ... @@ -945,15 +1124,15 @@ class Test { }; ``` -The typical usage, which basically simulates the behavior of a thrown -exception, is: +The typical usage, which basically simulates the behavior of a thrown exception, +is: -``` +```c++ TEST(FooTest, Bar) { Subroutine(); // Aborts if Subroutine() had a fatal failure. - if (HasFatalFailure()) - return; + if (HasFatalFailure()) return; + // The following won't be executed. ... } @@ -962,25 +1141,24 @@ TEST(FooTest, Bar) { If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test fixture, you must add the `::testing::Test::` prefix, as in: -``` -if (::testing::Test::HasFatalFailure()) - return; +```c++ +if (::testing::Test::HasFatalFailure()) return; ``` -Similarly, `HasNonfatalFailure()` returns `true` if the current test -has at least one non-fatal failure, and `HasFailure()` returns `true` -if the current test has at least one failure of either kind. +Similarly, `HasNonfatalFailure()` returns `true` if the current test has at +least one non-fatal failure, and `HasFailure()` returns `true` if the current +test has at least one failure of either kind. -_Availability:_ Linux, Windows, Mac. `HasNonfatalFailure()` and -`HasFailure()` are available since version 1.4.0. +**Availability**: Linux, Windows, Mac. -# Logging Additional Information # +## Logging Additional Information -In your test code, you can call `RecordProperty("key", value)` to log -additional information, where `value` can be either a string or an `int`. The _last_ value recorded for a key will be emitted to the XML output -if you specify one. For example, the test +In your test code, you can call `RecordProperty("key", value)` to log additional +information, where `value` can be either a string or an `int`. The *last* value +recorded for a key will be emitted to the [XML output](#XmlReport) if you +specify one. For example, the test -``` +```c++ TEST_F(WidgetUsageTest, MinAndMaxWidgets) { RecordProperty("MaximumWidgets", ComputeMaxUsage()); RecordProperty("MinimumWidgets", ComputeMinUsage()); @@ -989,51 +1167,63 @@ TEST_F(WidgetUsageTest, MinAndMaxWidgets) { will output XML like this: +```xml + ... + + ... ``` -... - -... -``` - -_Note_: - * `RecordProperty()` is a static member of the `Test` class. Therefore it needs to be prefixed with `::testing::Test::` if used outside of the `TEST` body and the test fixture class. - * `key` must be a valid XML attribute name, and cannot conflict with the ones already used by Google Test (`name`, `status`, `time`, `classname`, `type_param`, and `value_param`). - * Calling `RecordProperty()` outside of the lifespan of a test is allowed. If it's called outside of a test but between a test case's `SetUpTestCase()` and `TearDownTestCase()` methods, it will be attributed to the XML element for the test case. If it's called outside of all test cases (e.g. in a test environment), it will be attributed to the top-level XML element. - -_Availability_: Linux, Windows, Mac. -# Sharing Resources Between Tests in the Same Test Case # +> NOTE: +> +> * `RecordProperty()` is a static member of the `Test` class. Therefore it +> needs to be prefixed with `::testing::Test::` if used outside of the +> `TEST` body and the test fixture class. +> * `*key*` must be a valid XML attribute name, and cannot conflict with the +> ones already used by googletest (`name`, `status`, `time`, `classname`, +> `type_param`, and `value_param`). +> * Calling `RecordProperty()` outside of the lifespan of a test is allowed. +> If it's called outside of a test but between a test case's +> `SetUpTestCase()` and `TearDownTestCase()` methods, it will be attributed +> to the XML element for the test case. If it's called outside of all test +> cases (e.g. in a test environment), it will be attributed to the top-level +> XML element. +**Availability**: Linux, Windows, Mac. +## Sharing Resources Between Tests in the Same Test Case -Google Test creates a new test fixture object for each test in order to make +googletest creates a new test fixture object for each test in order to make tests independent and easier to debug. However, sometimes tests use resources that are expensive to set up, making the one-copy-per-test model prohibitively expensive. -If the tests don't change the resource, there's no harm in them sharing a -single resource copy. So, in addition to per-test set-up/tear-down, Google Test +If the tests don't change the resource, there's no harm in their sharing a +single resource copy. So, in addition to per-test set-up/tear-down, googletest also supports per-test-case set-up/tear-down. To use it: - 1. In your test fixture class (say `FooTest` ), define as `static` some member variables to hold the shared resources. - 1. In the same test fixture class, define a `static void SetUpTestCase()` function (remember not to spell it as **`SetupTestCase`** with a small `u`!) to set up the shared resources and a `static void TearDownTestCase()` function to tear them down. - -That's it! Google Test automatically calls `SetUpTestCase()` before running the -_first test_ in the `FooTest` test case (i.e. before creating the first -`FooTest` object), and calls `TearDownTestCase()` after running the _last test_ -in it (i.e. after deleting the last `FooTest` object). In between, the tests -can use the shared resources. +1. In your test fixture class (say `FooTest` ), declare as `static` some member + variables to hold the shared resources. +1. Outside your test fixture class (typically just below it), define those + member variables, optionally giving them initial values. +1. In the same test fixture class, define a `static void SetUpTestCase()` + function (remember not to spell it as **`SetupTestCase`** with a small `u`!) + to set up the shared resources and a `static void TearDownTestCase()` + function to tear them down. + +That's it! googletest automatically calls `SetUpTestCase()` before running the +*first test* in the `FooTest` test case (i.e. before creating the first +`FooTest` object), and calls `TearDownTestCase()` after running the *last test* +in it (i.e. after deleting the last `FooTest` object). In between, the tests can +use the shared resources. Remember that the test order is undefined, so your code can't depend on a test -preceding or following another. Also, the tests must either not modify the -state of any shared resource, or, if they do modify the state, they must -restore the state to its original value before passing control to the next -test. +preceding or following another. Also, the tests must either not modify the state +of any shared resource, or, if they do modify the state, they must restore the +state to its original value before passing control to the next test. Here's an example of per-test-case set-up and tear-down: -``` + +```c++ class FooTest : public ::testing::Test { protected: // Per-test-case set-up. @@ -1051,8 +1241,10 @@ class FooTest : public ::testing::Test { shared_resource_ = NULL; } - // You can define per-test set-up and tear-down logic as usual. + // You can define per-test set-up logic as usual. virtual void SetUp() { ... } + + // You can define per-test tear-down logic as usual. virtual void TearDown() { ... } // Some expensive resource shared by all tests. @@ -1062,16 +1254,21 @@ class FooTest : public ::testing::Test { T* FooTest::shared_resource_ = NULL; TEST_F(FooTest, Test1) { - ... you can refer to shared_resource here ... + ... you can refer to shared_resource_ here ... } + TEST_F(FooTest, Test2) { - ... you can refer to shared_resource here ... + ... you can refer to shared_resource_ here ... } ``` -_Availability:_ Linux, Windows, Mac. +NOTE: Though the above code declares `SetUpTestCase()` protected, it may +sometimes be necessary to declare it public, such as when using it with +`TEST_P`. + +**Availability**: Linux, Windows, Mac. -# Global Set-Up and Tear-Down # +## Global Set-Up and Tear-Down Just as you can do set-up and tear-down at the test level and the test case level, you can also do it at the test program level. Here's how. @@ -1079,21 +1276,23 @@ level, you can also do it at the test program level. Here's how. First, you subclass the `::testing::Environment` class to define a test environment, which knows how to set-up and tear-down: -``` +```c++ class Environment { public: virtual ~Environment() {} + // Override this to define how to set up the environment. virtual void SetUp() {} + // Override this to define how to tear down the environment. virtual void TearDown() {} }; ``` -Then, you register an instance of your environment class with Google Test by +Then, you register an instance of your environment class with googletest by calling the `::testing::AddGlobalTestEnvironment()` function: -``` +```c++ Environment* AddGlobalTestEnvironment(Environment* env); ``` @@ -1105,79 +1304,58 @@ It's OK to register multiple environment objects. In this case, their `SetUp()` will be called in the order they are registered, and their `TearDown()` will be called in the reverse order. -Note that Google Test takes ownership of the registered environment objects. +Note that googletest takes ownership of the registered environment objects. Therefore **do not delete them** by yourself. -You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is -called, probably in `main()`. If you use `gtest_main`, you need to call -this before `main()` starts for it to take effect. One way to do this is to -define a global variable like this: +You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called, +probably in `main()`. If you use `gtest_main`, you need to call this before +`main()` starts for it to take effect. One way to do this is to define a global +variable like this: -``` -::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment); +```c++ +::testing::Environment* const foo_env = + ::testing::AddGlobalTestEnvironment(new FooEnvironment); ``` However, we strongly recommend you to write your own `main()` and call `AddGlobalTestEnvironment()` there, as relying on initialization of global -variables makes the code harder to read and may cause problems when you -register multiple environments from different translation units and the -environments have dependencies among them (remember that the compiler doesn't -guarantee the order in which global variables from different translation units -are initialized). - -_Availability:_ Linux, Windows, Mac. +variables makes the code harder to read and may cause problems when you register +multiple environments from different translation units and the environments have +dependencies among them (remember that the compiler doesn't guarantee the order +in which global variables from different translation units are initialized). + +## Value-Parameterized Tests + +*Value-parameterized tests* allow you to test your code with different +parameters without writing multiple copies of the same test. This is useful in a +number of situations, for example: + +* You have a piece of code whose behavior is affected by one or more + command-line flags. You want to make sure your code performs correctly for + various values of those flags. +* You want to test different implementations of an OO interface. +* You want to test your code over various inputs (a.k.a. data-driven testing). + This feature is easy to abuse, so please exercise your good sense when doing + it! + +### How to Write Value-Parameterized Tests + +To write value-parameterized tests, first you should define a fixture class. It +must be derived from both `::testing::Test` and +`::testing::WithParamInterface` (the latter is a pure interface), where `T` +is the type of your parameter values. For convenience, you can just derive the +fixture class from `::testing::TestWithParam`, which itself is derived from +both `::testing::Test` and `::testing::WithParamInterface`. `T` can be any +copyable type. If it's a raw pointer, you are responsible for managing the +lifespan of the pointed values. + +NOTE: If your test fixture defines `SetUpTestCase()` or `TearDownTestCase()` +they must be declared **public** rather than **protected** in order to use +`TEST_P`. - -# Value Parameterized Tests # - -_Value-parameterized tests_ allow you to test your code with different -parameters without writing multiple copies of the same test. - -Suppose you write a test for your code and then realize that your code is affected by a presence of a Boolean command line flag. - -``` -TEST(MyCodeTest, TestFoo) { - // A code to test foo(). -} -``` - -Usually people factor their test code into a function with a Boolean parameter in such situations. The function sets the flag, then executes the testing code. - -``` -void TestFooHelper(bool flag_value) { - flag = flag_value; - // A code to test foo(). -} - -TEST(MyCodeTest, TestFoo) { - TestFooHelper(false); - TestFooHelper(true); -} -``` - -But this setup has serious drawbacks. First, when a test assertion fails in your tests, it becomes unclear what value of the parameter caused it to fail. You can stream a clarifying message into your `EXPECT`/`ASSERT` statements, but it you'll have to do it with all of them. Second, you have to add one such helper function per test. What if you have ten tests? Twenty? A hundred? - -Value-parameterized tests will let you write your test only once and then easily instantiate and run it with an arbitrary number of parameter values. - -Here are some other situations when value-parameterized tests come handy: - - * You want to test different implementations of an OO interface. - * You want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it! - -## How to Write Value-Parameterized Tests ## - -To write value-parameterized tests, first you should define a fixture -class. It must be derived from both `::testing::Test` and -`::testing::WithParamInterface` (the latter is a pure interface), -where `T` is the type of your parameter values. For convenience, you -can just derive the fixture class from `::testing::TestWithParam`, -which itself is derived from both `::testing::Test` and -`::testing::WithParamInterface`. `T` can be any copyable type. If -it's a raw pointer, you are responsible for managing the lifespan of -the pointed values. - -``` -class FooTest : public ::testing::TestWithParam { +```c++ +class FooTest : + public ::testing::TestWithParam { // You can implement all the usual fixture class members here. // To access the test parameter, call GetParam() from class // TestWithParam. @@ -1193,11 +1371,11 @@ class BarTest : public BaseTest, }; ``` -Then, use the `TEST_P` macro to define as many test patterns using -this fixture as you want. The `_P` suffix is for "parameterized" or -"pattern", whichever you prefer to think. +Then, use the `TEST_P` macro to define as many test patterns using this fixture +as you want. The `_P` suffix is for "parameterized" or "pattern", whichever you +prefer to think. -``` +```c++ TEST_P(FooTest, DoesBlah) { // Inside a test, access the test parameter with the GetParam() method // of the TestWithParam class: @@ -1210,50 +1388,62 @@ TEST_P(FooTest, HasBlahBlah) { } ``` -Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test -case with any set of parameters you want. Google Test defines a number of -functions for generating test parameters. They return what we call -(surprise!) _parameter generators_. Here is a summary of them, -which are all in the `testing` namespace: +Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test case with +any set of parameters you want. googletest defines a number of functions for +generating test parameters. They return what we call (surprise!) *parameter +generators*. Here is a summary of them, which are all in the `testing` +namespace: -| `Range(begin, end[, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | -|:----------------------------|:------------------------------------------------------------------------------------------------------------------| -| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | -| `ValuesIn(container)` and `ValuesIn(begin, end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. `container`, `begin`, and `end` can be expressions whose values are determined at run time. | -| `Bool()` | Yields sequence `{false, true}`. | -| `Combine(g1, g2, ..., gN)` | Yields all combinations (the Cartesian product for the math savvy) of the values generated by the `N` generators. This is only available if your system provides the `` header. If you are sure your system does, and Google Test disagrees, you can override it by defining `GTEST_HAS_TR1_TUPLE=1`. See comments in [include/gtest/internal/gtest-port.h](../include/gtest/internal/gtest-port.h) for more information. | +| Parameter Generator | Behavior | +| ---------------------------- | ------------------------------------------- | +| `Range(begin, end [, step])` | Yields values `{begin, begin+step, | +: : begin+step+step, ...}`. The values do not : +: : include `end`. `step` defaults to 1. : +| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | +| `ValuesIn(container)` and | Yields values from a C-style array, an | +: `ValuesIn(begin,end)` : STL-style container, or an iterator range : +: : `[begin, end)`. : +| `Bool()` | Yields sequence `{false, true}`. | +| `Combine(g1, g2, ..., gN)` | Yields all combinations (Cartesian product) | +: : as std\:\:tuples of the values generated by : +: : the `N` generators. : -For more details, see the comments at the definitions of these functions in the [source code](../include/gtest/gtest-param-test.h). +For more details, see the comments at the definitions of these functions. -The following statement will instantiate tests from the `FooTest` test case -each with parameter values `"meeny"`, `"miny"`, and `"moe"`. +The following statement will instantiate tests from the `FooTest` test case each +with parameter values `"meeny"`, `"miny"`, and `"moe"`. -``` +```c++ INSTANTIATE_TEST_CASE_P(InstantiationName, FooTest, ::testing::Values("meeny", "miny", "moe")); ``` -To distinguish different instances of the pattern (yes, you can -instantiate it more than once), the first argument to -`INSTANTIATE_TEST_CASE_P` is a prefix that will be added to the actual -test case name. Remember to pick unique prefixes for different -instantiations. The tests from the instantiation above will have these -names: +NOTE: The code above must be placed at global or namespace scope, not at +function scope. - * `InstantiationName/FooTest.DoesBlah/0` for `"meeny"` - * `InstantiationName/FooTest.DoesBlah/1` for `"miny"` - * `InstantiationName/FooTest.DoesBlah/2` for `"moe"` - * `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"` - * `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"` - * `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"` +NOTE: Don't forget this step! If you do your test will silently pass, but none +of its cases will ever run! -You can use these names in [--gtest\_filter](#running-a-subset-of-the-tests). +To distinguish different instances of the pattern (yes, you can instantiate it +more than once), the first argument to `INSTANTIATE_TEST_CASE_P` is a prefix +that will be added to the actual test case name. Remember to pick unique +prefixes for different instantiations. The tests from the instantiation above +will have these names: -This statement will instantiate all tests from `FooTest` again, each -with parameter values `"cat"` and `"dog"`: +* `InstantiationName/FooTest.DoesBlah/0` for `"meeny"` +* `InstantiationName/FooTest.DoesBlah/1` for `"miny"` +* `InstantiationName/FooTest.DoesBlah/2` for `"moe"` +* `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"` +* `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"` +* `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"` -``` +You can use these names in [`--gtest_filter`](#TestFilter). + +This statement will instantiate all tests from `FooTest` again, each with +parameter values `"cat"` and `"dog"`: + +```c++ const char* pets[] = {"cat", "dog"}; INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ::testing::ValuesIn(pets)); @@ -1261,65 +1451,91 @@ INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, The tests from the instantiation above will have these names: - * `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"` - * `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"` - * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"` - * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"` +* `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"` +* `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"` +* `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"` +* `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"` -Please note that `INSTANTIATE_TEST_CASE_P` will instantiate _all_ -tests in the given test case, whether their definitions come before or -_after_ the `INSTANTIATE_TEST_CASE_P` statement. +Please note that `INSTANTIATE_TEST_CASE_P` will instantiate *all* tests in the +given test case, whether their definitions come before or *after* the +`INSTANTIATE_TEST_CASE_P` statement. -You can see -[these](../samples/sample7_unittest.cc) -[files](../samples/sample8_unittest.cc) for more examples. +You can see sample7_unittest.cc and sample8_unittest.cc for more examples. -_Availability_: Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.2.0. +**Availability**: Linux, Windows (requires MSVC 8.0 or above), Mac -## Creating Value-Parameterized Abstract Tests ## +### Creating Value-Parameterized Abstract Tests -In the above, we define and instantiate `FooTest` in the same source -file. Sometimes you may want to define value-parameterized tests in a -library and let other people instantiate them later. This pattern is -known as abstract tests. As an example of its application, when you -are designing an interface you can write a standard suite of abstract -tests (perhaps using a factory function as the test parameter) that -all implementations of the interface are expected to pass. When -someone implements the interface, they can instantiate your suite to get -all the interface-conformance tests for free. +In the above, we define and instantiate `FooTest` in the *same* source file. +Sometimes you may want to define value-parameterized tests in a library and let +other people instantiate them later. This pattern is known as *abstract tests*. +As an example of its application, when you are designing an interface you can +write a standard suite of abstract tests (perhaps using a factory function as +the test parameter) that all implementations of the interface are expected to +pass. When someone implements the interface, they can instantiate your suite to +get all the interface-conformance tests for free. To define abstract tests, you should organize your code like this: - 1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) in a header file, say `foo_param_test.h`. Think of this as _declaring_ your abstract tests. - 1. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes `foo_param_test.h`. Think of this as _implementing_ your abstract tests. +1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) + in a header file, say `foo_param_test.h`. Think of this as *declaring* your + abstract tests. +1. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes + `foo_param_test.h`. Think of this as *implementing* your abstract tests. + +Once they are defined, you can instantiate them by including `foo_param_test.h`, +invoking `INSTANTIATE_TEST_CASE_P()`, and depending on the library target that +contains `foo_param_test.cc`. You can instantiate the same abstract test case +multiple times, possibly in different source files. -Once they are defined, you can instantiate them by including -`foo_param_test.h`, invoking `INSTANTIATE_TEST_CASE_P()`, and linking -with `foo_param_test.cc`. You can instantiate the same abstract test -case multiple times, possibly in different source files. +### Specifying Names for Value-Parameterized Test Parameters -# Typed Tests # +The optional last argument to `INSTANTIATE_TEST_CASE_P()` allows the user to +specify a function or functor that generates custom test name suffixes based on +the test parameters. The function should accept one argument of type +`testing::TestParamInfo`, and return `std::string`. -Suppose you have multiple implementations of the same interface and -want to make sure that all of them satisfy some common requirements. -Or, you may have defined several types that are supposed to conform to -the same "concept" and you want to verify it. In both cases, you want -the same test logic repeated for different types. +`testing::PrintToStringParamName` is a builtin test suffix generator that +returns the value of `testing::PrintToString(GetParam())`. It does not work for +`std::string` or C strings. -While you can write one `TEST` or `TEST_F` for each type you want to -test (and you may even factor the test logic into a function template -that you invoke from the `TEST`), it's tedious and doesn't scale: -if you want _m_ tests over _n_ types, you'll end up writing _m\*n_ -`TEST`s. +NOTE: test names must be non-empty, unique, and may only contain ASCII +alphanumeric characters. In particular, they [should not contain +underscores](https://g3doc.corp.google.com/third_party/googletest/googletest/g3doc/faq.md#no-underscores). -_Typed tests_ allow you to repeat the same test logic over a list of -types. You only need to write the test logic once, although you must -know the type list when writing typed tests. Here's how you do it: +```c++ +class MyTestCase : public testing::TestWithParam {}; -First, define a fixture class template. It should be parameterized -by a type. Remember to derive it from `::testing::Test`: +TEST_P(MyTestCase, MyTest) +{ + std::cout << "Example Test Param: " << GetParam() << std::endl; +} +INSTANTIATE_TEST_CASE_P(MyGroup, MyTestCase, testing::Range(0, 10), + testing::PrintToStringParamName()); ``` + +## Typed Tests + +Suppose you have multiple implementations of the same interface and want to make +sure that all of them satisfy some common requirements. Or, you may have defined +several types that are supposed to conform to the same "concept" and you want to +verify it. In both cases, you want the same test logic repeated for different +types. + +While you can write one `TEST` or `TEST_F` for each type you want to test (and +you may even factor the test logic into a function template that you invoke from +the `TEST`), it's tedious and doesn't scale: if you want `m` tests over `n` +types, you'll end up writing `m*n` `TEST`s. + +*Typed tests* allow you to repeat the same test logic over a list of types. You +only need to write the test logic once, although you must know the type list +when writing typed tests. Here's how you do it: + +First, define a fixture class template. It should be parameterized by a type. +Remember to derive it from `::testing::Test`: + +```c++ template class FooTest : public ::testing::Test { public: @@ -1330,22 +1546,22 @@ class FooTest : public ::testing::Test { }; ``` -Next, associate a list of types with the test case, which will be -repeated for each type in the list: +Next, associate a list of types with the test case, which will be repeated for +each type in the list: -``` -typedef ::testing::Types MyTypes; +```c++ +using MyTypes = ::testing::Types; TYPED_TEST_CASE(FooTest, MyTypes); ``` -The `typedef` is necessary for the `TYPED_TEST_CASE` macro to parse -correctly. Otherwise the compiler will think that each comma in the -type list introduces a new macro argument. +The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_CASE` +macro to parse correctly. Otherwise the compiler will think that each comma in +the type list introduces a new macro argument. -Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test -for this test case. You can repeat this as many times as you want: +Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test for this +test case. You can repeat this as many times as you want: -``` +```c++ TYPED_TEST(FooTest, DoesBlah) { // Inside a test, refer to the special name TypeParam to get the type // parameter. Since we are inside a derived class template, C++ requires @@ -1359,6 +1575,7 @@ TYPED_TEST(FooTest, DoesBlah) { // To refer to typedefs in the fixture, add the 'typename TestFixture::' // prefix. The 'typename' is required to satisfy the compiler. typename TestFixture::List values; + values.push_back(n); ... } @@ -1366,29 +1583,27 @@ TYPED_TEST(FooTest, DoesBlah) { TYPED_TEST(FooTest, HasPropertyA) { ... } ``` -You can see [`samples/sample6_unittest.cc`](../samples/sample6_unittest.cc) for a complete example. +You can see sample6_unittest.cc -_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; -since version 1.1.0. +**Availability**: Linux, Windows (requires MSVC 8.0 or above), Mac -# Type-Parameterized Tests # +## Type-Parameterized Tests -_Type-parameterized tests_ are like typed tests, except that they -don't require you to know the list of types ahead of time. Instead, -you can define the test logic first and instantiate it with different -type lists later. You can even instantiate it more than once in the -same program. +*Type-parameterized tests* are like typed tests, except that they don't require +you to know the list of types ahead of time. Instead, you can define the test +logic first and instantiate it with different type lists later. You can even +instantiate it more than once in the same program. -If you are designing an interface or concept, you can define a suite -of type-parameterized tests to verify properties that any valid -implementation of the interface/concept should have. Then, the author -of each implementation can just instantiate the test suite with his -type to verify that it conforms to the requirements, without having to -write similar tests repeatedly. Here's an example: +If you are designing an interface or concept, you can define a suite of +type-parameterized tests to verify properties that any valid implementation of +the interface/concept should have. Then, the author of each implementation can +just instantiate the test suite with their type to verify that it conforms to +the requirements, without having to write similar tests repeatedly. Here's an +example: First, define a fixture class template, as we did with typed tests: -``` +```c++ template class FooTest : public ::testing::Test { ... @@ -1397,17 +1612,14 @@ class FooTest : public ::testing::Test { Next, declare that you will define a type-parameterized test case: -``` +```c++ TYPED_TEST_CASE_P(FooTest); ``` -The `_P` suffix is for "parameterized" or "pattern", whichever you -prefer to think. - -Then, use `TYPED_TEST_P()` to define a type-parameterized test. You -can repeat this as many times as you want: +Then, use `TYPED_TEST_P()` to define a type-parameterized test. You can repeat +this as many times as you want: -``` +```c++ TYPED_TEST_P(FooTest, DoesBlah) { // Inside a test, refer to TypeParam to get the type parameter. TypeParam n = 0; @@ -1418,204 +1630,212 @@ TYPED_TEST_P(FooTest, HasPropertyA) { ... } ``` Now the tricky part: you need to register all test patterns using the -`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them. -The first argument of the macro is the test case name; the rest are -the names of the tests in this test case: +`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them. The first +argument of the macro is the test case name; the rest are the names of the tests +in this test case: -``` +```c++ REGISTER_TYPED_TEST_CASE_P(FooTest, DoesBlah, HasPropertyA); ``` -Finally, you are free to instantiate the pattern with the types you -want. If you put the above code in a header file, you can `#include` -it in multiple C++ source files and instantiate it multiple times. +Finally, you are free to instantiate the pattern with the types you want. If you +put the above code in a header file, you can `#include` it in multiple C++ +source files and instantiate it multiple times. -``` +```c++ typedef ::testing::Types MyTypes; INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); ``` -To distinguish different instances of the pattern, the first argument -to the `INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be -added to the actual test case name. Remember to pick unique prefixes -for different instances. +To distinguish different instances of the pattern, the first argument to the +`INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be added to the +actual test case name. Remember to pick unique prefixes for different instances. -In the special case where the type list contains only one type, you -can write that type directly without `::testing::Types<...>`, like this: +In the special case where the type list contains only one type, you can write +that type directly without `::testing::Types<...>`, like this: -``` +```c++ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); ``` -You can see `samples/sample6_unittest.cc` for a complete example. +You can see `sample6_unittest.cc` for a complete example. -_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; -since version 1.1.0. +**Availability**: Linux, Windows (requires MSVC 8.0 or above), Mac -# Testing Private Code # +## Testing Private Code If you change your software's internal implementation, your tests should not -break as long as the change is not observable by users. Therefore, per the -_black-box testing principle_, most of the time you should test your code -through its public interfaces. +break as long as the change is not observable by users. Therefore, **per the +black-box testing principle, most of the time you should test your code through +its public interfaces.** + +**If you still find yourself needing to test internal implementation code, +consider if there's a better design.** The desire to test internal +implementation is often a sign that the class is doing too much. Consider +extracting an implementation class, and testing it. Then use that implementation +class in the original class. + +If you absolutely have to test non-public interface code though, you can. There +are two cases to consider: + +* Static functions ( *not* the same as static member functions!) or unnamed + namespaces, and +* Private or protected class members + +To test them, we use the following special techniques: + +* Both static functions and definitions/declarations in an unnamed namespace + are only visible within the same translation unit. To test them, you can + `#include` the entire `.cc` file being tested in your `*_test.cc` file. + (#including `.cc` files is not a good way to reuse code - you should not do + this in production code!) + + However, a better approach is to move the private code into the + `foo::internal` namespace, where `foo` is the namespace your project + normally uses, and put the private declarations in a `*-internal.h` file. + Your production `.cc` files and your tests are allowed to include this + internal header, but your clients are not. This way, you can fully test your + internal implementation without leaking it to your clients. + +* Private class members are only accessible from within the class or by + friends. To access a class' private members, you can declare your test + fixture as a friend to the class and define accessors in your fixture. Tests + using the fixture can then access the private members of your production + class via the accessors in the fixture. Note that even though your fixture + is a friend to your production class, your tests are not automatically + friends to it, as they are technically defined in sub-classes of the + fixture. + + Another way to test private members is to refactor them into an + implementation class, which is then declared in a `*-internal.h` file. Your + clients aren't allowed to include this header but your tests can. Such is + called the + [Pimpl](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/the-c-pimpl-r1794/) + (Private Implementation) idiom. + + Or, you can declare an individual test as a friend of your class by adding + this line in the class body: + + ```c++ + FRIEND_TEST(TestCaseName, TestName); + ``` + + For example, + + ```c++ + // foo.h -If you still find yourself needing to test internal implementation code, -consider if there's a better design that wouldn't require you to do so. If you -absolutely have to test non-public interface code though, you can. There are -two cases to consider: +#include "gtest/gtest_prod.h" - * Static functions (_not_ the same as static member functions!) or unnamed namespaces, and - * Private or protected class members. + class Foo { + ... + private: + FRIEND_TEST(FooTest, BarReturnsZeroOnNull); -## Static Functions ## + int Bar(void* x); + }; -Both static functions and definitions/declarations in an unnamed namespace are -only visible within the same translation unit. To test them, you can `#include` -the entire `.cc` file being tested in your `*_test.cc` file. (`#include`ing `.cc` -files is not a good way to reuse code - you should not do this in production -code!) + // foo_test.cc + ... + TEST(FooTest, BarReturnsZeroOnNull) { + Foo foo; + EXPECT_EQ(0, foo.Bar(NULL)); // Uses Foo's private member Bar(). + } + ``` -However, a better approach is to move the private code into the -`foo::internal` namespace, where `foo` is the namespace your project normally -uses, and put the private declarations in a `*-internal.h` file. Your -production `.cc` files and your tests are allowed to include this internal -header, but your clients are not. This way, you can fully test your internal -implementation without leaking it to your clients. + Pay special attention when your class is defined in a namespace, as you + should define your test fixtures and tests in the same namespace if you want + them to be friends of your class. For example, if the code to be tested + looks like: -## Private Class Members ## + ```c++ + namespace my_namespace { -Private class members are only accessible from within the class or by friends. -To access a class' private members, you can declare your test fixture as a -friend to the class and define accessors in your fixture. Tests using the -fixture can then access the private members of your production class via the -accessors in the fixture. Note that even though your fixture is a friend to -your production class, your tests are not automatically friends to it, as they -are technically defined in sub-classes of the fixture. + class Foo { + friend class FooTest; + FRIEND_TEST(FooTest, Bar); + FRIEND_TEST(FooTest, Baz); + ... definition of the class Foo ... + }; -Another way to test private members is to refactor them into an implementation -class, which is then declared in a `*-internal.h` file. Your clients aren't -allowed to include this header but your tests can. Such is called the Pimpl -(Private Implementation) idiom. + } // namespace my_namespace + ``` -Or, you can declare an individual test as a friend of your class by adding this -line in the class body: + Your test code should be something like: -``` -FRIEND_TEST(TestCaseName, TestName); -``` + ```c++ + namespace my_namespace { -For example, -``` -// foo.h -#include "gtest/gtest_prod.h" + class FooTest : public ::testing::Test { + protected: + ... + }; -// Defines FRIEND_TEST. -class Foo { - ... - private: - FRIEND_TEST(FooTest, BarReturnsZeroOnNull); - int Bar(void* x); -}; + TEST_F(FooTest, Bar) { ... } + TEST_F(FooTest, Baz) { ... } -// foo_test.cc -... -TEST(FooTest, BarReturnsZeroOnNull) { - Foo foo; - EXPECT_EQ(0, foo.Bar(NULL)); - // Uses Foo's private member Bar(). -} -``` + } // namespace my_namespace + ``` -Pay special attention when your class is defined in a namespace, as you should -define your test fixtures and tests in the same namespace if you want them to -be friends of your class. For example, if the code to be tested looks like: -``` -namespace my_namespace { + ## "Catching" Failures -class Foo { - friend class FooTest; - FRIEND_TEST(FooTest, Bar); - FRIEND_TEST(FooTest, Baz); - ... - definition of the class Foo - ... -}; +If you are building a testing utility on top of googletest, you'll want to test +your utility. What framework would you use to test it? googletest, of course. -} // namespace my_namespace -``` +The challenge is to verify that your testing utility reports failures correctly. +In frameworks that report a failure by throwing an exception, you could catch +the exception and assert on it. But googletest doesn't use exceptions, so how do +we test that a piece of code generates an expected failure? -Your test code should be something like: +gunit-spi.h contains some constructs to do this. After #including this header, +you can use +```c++ + EXPECT_FATAL_FAILURE(statement, substring); ``` -namespace my_namespace { -class FooTest : public ::testing::Test { - protected: - ... -}; -TEST_F(FooTest, Bar) { ... } -TEST_F(FooTest, Baz) { ... } +to assert that `statement` generates a fatal (e.g. `ASSERT_*`) failure in the +current thread whose message contains the given `substring`, or use -} // namespace my_namespace +```c++ + EXPECT_NONFATAL_FAILURE(statement, substring); ``` -# Catching Failures # - -If you are building a testing utility on top of Google Test, you'll -want to test your utility. What framework would you use to test it? -Google Test, of course. - -The challenge is to verify that your testing utility reports failures -correctly. In frameworks that report a failure by throwing an -exception, you could catch the exception and assert on it. But Google -Test doesn't use exceptions, so how do we test that a piece of code -generates an expected failure? - -`"gtest/gtest-spi.h"` contains some constructs to do this. After -`#include`ing this header, you can use - -| `EXPECT_FATAL_FAILURE(`_statement, substring_`);` | -|:--------------------------------------------------| +if you are expecting a non-fatal (e.g. `EXPECT_*`) failure. -to assert that _statement_ generates a fatal (e.g. `ASSERT_*`) failure -whose message contains the given _substring_, or use +Only failures in the current thread are checked to determine the result of this +type of expectations. If `statement` creates new threads, failures in these +threads are also ignored. If you want to catch failures in other threads as +well, use one of the following macros instead: -| `EXPECT_NONFATAL_FAILURE(`_statement, substring_`);` | -|:-----------------------------------------------------| +```c++ + EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substring); + EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring); +``` -if you are expecting a non-fatal (e.g. `EXPECT_*`) failure. +NOTE: Assertions from multiple threads are currently not supported on Windows. For technical reasons, there are some caveats: - 1. You cannot stream a failure message to either macro. - 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot reference local non-static variables or non-static members of `this` object. - 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot return a value. +1. You cannot stream a failure message to either macro. + +1. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot reference + local non-static variables or non-static members of `this` object. -_Note:_ Google Test is designed with threads in mind. Once the -synchronization primitives in `"gtest/internal/gtest-port.h"` have -been implemented, Google Test will become thread-safe, meaning that -you can then use assertions in multiple threads concurrently. Before -that, however, Google Test only supports single-threaded usage. Once -thread-safe, `EXPECT_FATAL_FAILURE()` and `EXPECT_NONFATAL_FAILURE()` -will capture failures in the current thread only. If _statement_ -creates new threads, failures in these threads will be ignored. If -you want to capture failures from all threads instead, you should use -the following macros: +1. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()()` cannot return a + value. -| `EXPECT_FATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | -|:-----------------------------------------------------------------| -| `EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | -# Getting the Current Test's Name # +## Getting the Current Test's Name Sometimes a function may need to know the name of the currently running test. For example, you may be using the `SetUp()` method of your test fixture to set the golden file name based on which test is running. The `::testing::TestInfo` class has this information: -``` +```c++ namespace testing { class TestInfo { @@ -1628,65 +1848,68 @@ class TestInfo { const char* name() const; }; -} // namespace testing +} ``` - -> To obtain a `TestInfo` object for the currently running test, call +To obtain a `TestInfo` object for the currently running test, call `current_test_info()` on the `UnitTest` singleton object: -``` -// Gets information about the currently running test. -// Do NOT delete the returned object - it's managed by the UnitTest class. -const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); -printf("We are in test %s of test case %s.\n", - test_info->name(), test_info->test_case_name()); +```c++ + // Gets information about the currently running test. + // Do NOT delete the returned object - it's managed by the UnitTest class. + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + + + + printf("We are in test %s of test case %s.\n", + test_info->name(), + test_info->test_case_name()); ``` `current_test_info()` returns a null pointer if no test is running. In -particular, you cannot find the test case name in `SetUpTestCase()`, -`TearDownTestCase()` (where you know the test case name implicitly), or +particular, you cannot find the test case name in `TestCaseSetUp()`, +`TestCaseTearDown()` (where you know the test case name implicitly), or functions called from them. -_Availability:_ Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -# Extending Google Test by Handling Test Events # +## Extending googletest by Handling Test Events -Google Test provides an event listener API to let you receive -notifications about the progress of a test program and test -failures. The events you can listen to include the start and end of -the test program, a test case, or a test method, among others. You may -use this API to augment or replace the standard console output, -replace the XML output, or provide a completely different form of -output, such as a GUI or a database. You can also use test events as +googletest provides an **event listener API** to let you receive notifications +about the progress of a test program and test failures. The events you can +listen to include the start and end of the test program, a test case, or a test +method, among others. You may use this API to augment or replace the standard +console output, replace the XML output, or provide a completely different form +of output, such as a GUI or a database. You can also use test events as checkpoints to implement a resource leak checker, for example. -_Availability:_ Linux, Windows, Mac; since v1.4.0. +**Availability**: Linux, Windows, Mac. -## Defining Event Listeners ## +### Defining Event Listeners -To define a event listener, you subclass either -[testing::TestEventListener](../include/gtest/gtest.h#L991) -or [testing::EmptyTestEventListener](../include/gtest/gtest.h#L1044). -The former is an (abstract) interface, where each pure virtual method
-can be overridden to handle a test event
(For example, when a test -starts, the `OnTestStart()` method will be called.). The latter provides -an empty implementation of all methods in the interface, such that a -subclass only needs to override the methods it cares about. +To define a event listener, you subclass either testing::TestEventListener or +testing::EmptyTestEventListener The former is an (abstract) interface, where +*each pure virtual method can be overridden to handle a test event* (For +example, when a test starts, the `OnTestStart()` method will be called.). The +latter provides an empty implementation of all methods in the interface, such +that a subclass only needs to override the methods it cares about. -When an event is fired, its context is passed to the handler function -as an argument. The following argument types are used: - * [UnitTest](../include/gtest/gtest.h#L1151) reflects the state of the entire test program, - * [TestCase](../include/gtest/gtest.h#L778) has information about a test case, which can contain one or more tests, - * [TestInfo](../include/gtest/gtest.h#L644) contains the state of a test, and - * [TestPartResult](../include/gtest/gtest-test-part.h#L47) represents the result of a test assertion. +When an event is fired, its context is passed to the handler function as an +argument. The following argument types are used: -An event handler function can examine the argument it receives to find -out interesting information about the event and the test program's -state. Here's an example: +* UnitTest reflects the state of the entire test program, +* TestCase has information about a test case, which can contain one or more + tests, +* TestInfo contains the state of a test, and +* TestPartResult represents the result of a test assertion. -``` +An event handler function can examine the argument it receives to find out +interesting information about the event and the test program's state. + +Here's an example: + +```c++ class MinimalistPrinter : public ::testing::EmptyTestEventListener { // Called before a test starts. virtual void OnTestStart(const ::testing::TestInfo& test_info) { @@ -1694,9 +1917,8 @@ state. Here's an example: test_info.test_case_name(), test_info.name()); } - // Called after a failed assertion or a SUCCEED() invocation. - virtual void OnTestPartResult( - const ::testing::TestPartResult& test_part_result) { + // Called after a failed assertion or a SUCCESS(). + virtual void OnTestPartResult(const ::testing::TestPartResult& test_part_result) { printf("%s in %s:%d\n%s\n", test_part_result.failed() ? "*** Failure" : "Success", test_part_result.file_name(), @@ -1712,105 +1934,88 @@ state. Here's an example: }; ``` -## Using Event Listeners ## +### Using Event Listeners -To use the event listener you have defined, add an instance of it to -the Google Test event listener list (represented by class -[TestEventListeners](../include/gtest/gtest.h#L1064) -- note the "s" at the end of the name) in your -`main()` function, before calling `RUN_ALL_TESTS()`: -``` +To use the event listener you have defined, add an instance of it to the +googletest event listener list (represented by class TestEventListeners - note +the "s" at the end of the name) in your `main()` function, before calling +`RUN_ALL_TESTS()`: + +```c++ int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); // Gets hold of the event listener list. ::testing::TestEventListeners& listeners = - ::testing::UnitTest::GetInstance()->listeners(); - // Adds a listener to the end. Google Test takes the ownership. + ::testing::UnitTest::GetInstance()->listeners(); + // Adds a listener to the end. googletest takes the ownership. listeners.Append(new MinimalistPrinter); return RUN_ALL_TESTS(); } ``` -There's only one problem: the default test result printer is still in -effect, so its output will mingle with the output from your minimalist -printer. To suppress the default printer, just release it from the -event listener list and delete it. You can do so by adding one line: -``` +There's only one problem: the default test result printer is still in effect, so +its output will mingle with the output from your minimalist printer. To suppress +the default printer, just release it from the event listener list and delete it. +You can do so by adding one line: + +```c++ ... delete listeners.Release(listeners.default_result_printer()); listeners.Append(new MinimalistPrinter); return RUN_ALL_TESTS(); ``` -Now, sit back and enjoy a completely different output from your -tests. For more details, you can read this -[sample](../samples/sample9_unittest.cc). +Now, sit back and enjoy a completely different output from your tests. For more +details, you can read this sample9_unittest.cc -You may append more than one listener to the list. When an `On*Start()` -or `OnTestPartResult()` event is fired, the listeners will receive it in -the order they appear in the list (since new listeners are added to -the end of the list, the default text printer and the default XML -generator will receive the event first). An `On*End()` event will be -received by the listeners in the _reverse_ order. This allows output by -listeners added later to be framed by output from listeners added -earlier. +You may append more than one listener to the list. When an `On*Start()` or +`OnTestPartResult()` event is fired, the listeners will receive it in the order +they appear in the list (since new listeners are added to the end of the list, +the default text printer and the default XML generator will receive the event +first). An `On*End()` event will be received by the listeners in the *reverse* +order. This allows output by listeners added later to be framed by output from +listeners added earlier. -## Generating Failures in Listeners ## +### Generating Failures in Listeners -You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, -`FAIL()`, etc) when processing an event. There are some restrictions: +You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, `FAIL()`, etc) +when processing an event. There are some restrictions: - 1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will cause `OnTestPartResult()` to be called recursively). - 1. A listener that handles `OnTestPartResult()` is not allowed to generate any failure. +1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will + cause `OnTestPartResult()` to be called recursively). +1. A listener that handles `OnTestPartResult()` is not allowed to generate any + failure. -When you add listeners to the listener list, you should put listeners -that handle `OnTestPartResult()` _before_ listeners that can generate -failures. This ensures that failures generated by the latter are -attributed to the right test by the former. +When you add listeners to the listener list, you should put listeners that +handle `OnTestPartResult()` *before* listeners that can generate failures. This +ensures that failures generated by the latter are attributed to the right test +by the former. -We have a sample of failure-raising listener -[here](../samples/sample10_unittest.cc). +We have a sample of failure-raising listener sample10_unittest.cc -# Running Test Programs: Advanced Options # +## Running Test Programs: Advanced Options -Google Test test programs are ordinary executables. Once built, you can run -them directly and affect their behavior via the following environment variables +googletest test programs are ordinary executables. Once built, you can run them +directly and affect their behavior via the following environment variables and/or command line flags. For the flags to work, your programs must call `::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. -To see a list of supported flags and their usage, please run your test -program with the `--help` flag. You can also use `-h`, `-?`, or `/?` -for short. This feature is added in version 1.3.0. - -If an option is specified both by an environment variable and by a -flag, the latter takes precedence. Most of the options can also be -set/read in code: to access the value of command line flag -`--gtest_foo`, write `::testing::GTEST_FLAG(foo)`. A common pattern is -to set the value of a flag before calling `::testing::InitGoogleTest()` -to change the default value of the flag: -``` -int main(int argc, char** argv) { - // Disables elapsed time by default. - ::testing::GTEST_FLAG(print_time) = false; +To see a list of supported flags and their usage, please run your test program +with the `--help` flag. You can also use `-h`, `-?`, or `/?` for short. - // This allows the user to override the flag on the command line. - ::testing::InitGoogleTest(&argc, argv); +If an option is specified both by an environment variable and by a flag, the +latter takes precedence. - return RUN_ALL_TESTS(); -} -``` +### Selecting Tests -## Selecting Tests ## - -This section shows various options for choosing which tests to run. - -### Listing Test Names ### +#### Listing Test Names Sometimes it is necessary to list the available tests in a program before running them so that a filter may be applied if needed. Including the flag `--gtest_list_tests` overrides all other flags and lists tests in the following format: -``` + +```none TestCase1. TestName1 TestName2 @@ -1821,39 +2026,44 @@ TestCase2. None of the tests listed are actually run if the flag is provided. There is no corresponding environment variable for this flag. -_Availability:_ Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -### Running a Subset of the Tests ### +#### Running a Subset of the Tests -By default, a Google Test program runs all tests the user has defined. -Sometimes, you want to run only a subset of the tests (e.g. for debugging or -quickly verifying a change). If you set the `GTEST_FILTER` environment variable -or the `--gtest_filter` flag to a filter string, Google Test will only run the -tests whose full names (in the form of `TestCaseName.TestName`) match the -filter. +By default, a googletest program runs all tests the user has defined. Sometimes, +you want to run only a subset of the tests (e.g. for debugging or quickly +verifying a change). If you set the `GTEST_FILTER` environment variable or the +`--gtest_filter` flag to a filter string, googletest will only run the tests +whose full names (in the form of `TestCaseName.TestName`) match the filter. The format of a filter is a '`:`'-separated list of wildcard patterns (called -the positive patterns) optionally followed by a '`-`' and another -'`:`'-separated pattern list (called the negative patterns). A test matches the -filter if and only if it matches any of the positive patterns but does not +the *positive patterns*) optionally followed by a '`-`' and another +'`:`'-separated pattern list (called the *negative patterns*). A test matches +the filter if and only if it matches any of the positive patterns but does not match any of the negative patterns. A pattern may contain `'*'` (matches any string) or `'?'` (matches any single -character). For convenience, the filter `'*-NegativePatterns'` can be also -written as `'-NegativePatterns'`. - -For example: +character). For convenience, the filter - * `./foo_test` Has no flag, and thus runs all its tests. - * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value. - * `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest`. - * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"`. - * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. - * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test case `FooTest` except `FooTest.Bar`. +`'*-NegativePatterns'` can be also written as `'-NegativePatterns'`. -_Availability:_ Linux, Windows, Mac. +For example: -### Temporarily Disabling Tests ### +* `./foo_test` Has no flag, and thus runs all its tests. +* `./foo_test --gtest_filter=*` Also runs everything, due to the single + match-everything `*` value. +* `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest` + . +* `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full + name contains either `"Null"` or `"Constructor"` . +* `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. +* `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test + case `FooTest` except `FooTest.Bar`. +* `./foo_test --gtest_filter=FooTest.*:BarTest.*-FooTest.Bar:BarTest.Foo` Runs + everything in test case `FooTest` except `FooTest.Bar` and everything in + test case `BarTest` except `BarTest.Foo`. + +#### Temporarily Disabling Tests If you have a broken test that you cannot fix right away, you can add the `DISABLED_` prefix to its name. This will exclude it from execution. This is @@ -1864,10 +2074,10 @@ If you need to disable all tests in a test case, you can either add `DISABLED_` to the front of the name of each test, or alternatively add it to the front of the test case name. -For example, the following tests won't be run by Google Test, even though they +For example, the following tests won't be run by googletest, even though they will still be compiled: -``` +```c++ // Tests that Foo does Abc. TEST(FooTest, DISABLED_DoesAbc) { ... } @@ -1877,140 +2087,164 @@ class DISABLED_BarTest : public ::testing::Test { ... }; TEST_F(DISABLED_BarTest, DoesXyz) { ... } ``` -_Note:_ This feature should only be used for temporary pain-relief. You still -have to fix the disabled tests at a later date. As a reminder, Google Test will -print a banner warning you if a test program contains any disabled tests. +NOTE: This feature should only be used for temporary pain-relief. You still have +to fix the disabled tests at a later date. As a reminder, googletest will print +a banner warning you if a test program contains any disabled tests. -_Tip:_ You can easily count the number of disabled tests you have -using `grep`. This number can be used as a metric for improving your -test quality. +TIP: You can easily count the number of disabled tests you have using `gsearch` +and/or `grep`. This number can be used as a metric for improving your test +quality. -_Availability:_ Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -### Temporarily Enabling Disabled Tests ### +#### Temporarily Enabling Disabled Tests -To include [disabled tests](#temporarily-disabling-tests) in test -execution, just invoke the test program with the -`--gtest_also_run_disabled_tests` flag or set the -`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other -than `0`. You can combine this with the -[--gtest\_filter](#running-a-subset-of-the-tests) flag to further select -which disabled tests to run. +To include disabled tests in test execution, just invoke the test program with +the `--gtest_also_run_disabled_tests` flag or set the +`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other than `0`. +You can combine this with the `--gtest_filter` flag to further select which +disabled tests to run. -_Availability:_ Linux, Windows, Mac; since version 1.3.0. +**Availability**: Linux, Windows, Mac. -## Repeating the Tests ## +### Repeating the Tests Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it will fail only 1% of the time, making it rather hard to reproduce the bug under a debugger. This can be a major source of frustration. -The `--gtest_repeat` flag allows you to repeat all (or selected) test methods -in a program many times. Hopefully, a flaky test will eventually fail and give -you a chance to debug. Here's how to use it: +The `--gtest_repeat` flag allows you to repeat all (or selected) test methods in +a program many times. Hopefully, a flaky test will eventually fail and give you +a chance to debug. Here's how to use it: -| `$ foo_test --gtest_repeat=1000` | Repeat foo\_test 1000 times and don't stop at failures. | -|:---------------------------------|:--------------------------------------------------------| -| `$ foo_test --gtest_repeat=-1` | A negative count means repeating forever. | -| `$ foo_test --gtest_repeat=1000 --gtest_break_on_failure` | Repeat foo\_test 1000 times, stopping at the first failure. This is especially useful when running under a debugger: when the testfails, it will drop into the debugger and you can then inspect variables and stacks. | -| `$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar` | Repeat the tests whose name matches the filter 1000 times. | +```none +$ foo_test --gtest_repeat=1000 +Repeat foo_test 1000 times and don't stop at failures. -If your test program contains global set-up/tear-down code registered -using `AddGlobalTestEnvironment()`, it will be repeated in each -iteration as well, as the flakiness may be in it. You can also specify -the repeat count by setting the `GTEST_REPEAT` environment variable. +$ foo_test --gtest_repeat=-1 +A negative count means repeating forever. -_Availability:_ Linux, Windows, Mac. +$ foo_test --gtest_repeat=1000 --gtest_break_on_failure +Repeat foo_test 1000 times, stopping at the first failure. This +is especially useful when running under a debugger: when the test +fails, it will drop into the debugger and you can then inspect +variables and stacks. -## Shuffling the Tests ## +$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar.* +Repeat the tests whose name matches the filter 1000 times. +``` + +If your test program contains [global set-up/tear-down](#GlobalSetUp) code, it +will be repeated in each iteration as well, as the flakiness may be in it. You +can also specify the repeat count by setting the `GTEST_REPEAT` environment +variable. + +**Availability**: Linux, Windows, Mac. + +### Shuffling the Tests You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` -environment variable to `1`) to run the tests in a program in a random -order. This helps to reveal bad dependencies between tests. - -By default, Google Test uses a random seed calculated from the current -time. Therefore you'll get a different order every time. The console -output includes the random seed value, such that you can reproduce an -order-related test failure later. To specify the random seed -explicitly, use the `--gtest_random_seed=SEED` flag (or set the -`GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer -between 0 and 99999. The seed value 0 is special: it tells Google Test -to do the default behavior of calculating the seed from the current +environment variable to `1`) to run the tests in a program in a random order. +This helps to reveal bad dependencies between tests. + +By default, googletest uses a random seed calculated from the current time. +Therefore you'll get a different order every time. The console output includes +the random seed value, such that you can reproduce an order-related test failure +later. To specify the random seed explicitly, use the `--gtest_random_seed=SEED` +flag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an +integer in the range [0, 99999]. The seed value 0 is special: it tells +googletest to do the default behavior of calculating the seed from the current time. -If you combine this with `--gtest_repeat=N`, Google Test will pick a -different random seed and re-shuffle the tests in each iteration. +If you combine this with `--gtest_repeat=N`, googletest will pick a different +random seed and re-shuffle the tests in each iteration. + +**Availability**: Linux, Windows, Mac. -_Availability:_ Linux, Windows, Mac; since v1.4.0. +### Controlling Test Output -## Controlling Test Output ## +#### Colored Terminal Output -This section teaches how to tweak the way test results are reported. +googletest can use colors in its terminal output to make it easier to spot the +important information: -### Colored Terminal Output ### +... +[----------] 1 test from FooTest +[ RUN ] FooTest.DoesAbc +[ OK ] FooTest.DoesAbc +[----------] 2 tests from BarTest +[ RUN ] BarTest.HasXyzProperty +[ OK ] BarTest.HasXyzProperty +[ RUN ] BarTest.ReturnsTrueOnSuccess +... some error messages ... +[ FAILED ] BarTest.ReturnsTrueOnSuccess +... +[==========] 30 tests from 14 test cases ran. +[ PASSED ] 28 tests. +[ FAILED ] 2 tests, listed below: +[ FAILED ] BarTest.ReturnsTrueOnSuccess +[ FAILED ] AnotherTest.DoesXyz -Google Test can use colors in its terminal output to make it easier to spot -the separation between tests, and whether tests passed. + 2 FAILED TESTS -You can set the GTEST\_COLOR environment variable or set the `--gtest_color` +You can set the `GTEST_COLOR` environment variable or the `--gtest_color` command line flag to `yes`, `no`, or `auto` (the default) to enable colors, -disable colors, or let Google Test decide. When the value is `auto`, Google -Test will use colors if and only if the output goes to a terminal and (on -non-Windows platforms) the `TERM` environment variable is set to `xterm` or -`xterm-color`. +disable colors, or let googletest decide. When the value is `auto`, googletest +will use colors if and only if the output goes to a terminal and (on non-Windows +platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`. -_Availability:_ Linux, Windows, Mac. +> +> **Availability**: Linux, Windows, Mac. -### Suppressing the Elapsed Time ### +#### Suppressing the Elapsed Time -By default, Google Test prints the time it takes to run each test. To -suppress that, run the test program with the `--gtest_print_time=0` -command line flag. Setting the `GTEST_PRINT_TIME` environment -variable to `0` has the same effect. - -_Availability:_ Linux, Windows, Mac. (In Google Test 1.3.0 and lower, -the default behavior is that the elapsed time is **not** printed.) +By default, googletest prints the time it takes to run each test. To disable +that, run the test program with the `--gtest_print_time=0` command line flag, or +set the GTEST_PRINT_TIME environment variable to `0`. **Availability**: Linux, Windows, Mac. #### Suppressing UTF-8 Text Output -In case of assertion failures, gUnit prints expected and actual values of type -`string` both as hex-encoded strings as well as in readable UTF-8 text if they -contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 text -because, for example, you don't have an UTF-8 compatible output medium, run the -test program with `--gunit_print_utf8=0` or set the `GUNIT_PRINT_UTF8` +In case of assertion failures, googletest prints expected and actual values of +type `string` both as hex-encoded strings as well as in readable UTF-8 text if +they contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 +text because, for example, you don't have an UTF-8 compatible output medium, run +the test program with `--gtest_print_utf8=0` or set the `GTEST_PRINT_UTF8` environment variable to `0`. -### Generating an XML Report ### +**Availability**: Linux, Windows, Mac. + -Google Test can emit a detailed XML report to a file in addition to its normal -textual output. The report contains the duration of each test, and thus can -help you identify slow tests. +#### Generating an XML Report + +googletest can emit a detailed XML report to a file in addition to its normal +textual output. The report contains the duration of each test, and thus can help +you identify slow tests. The report is also used by the http://unittest +dashboard to show per-test-method error messages. To generate the XML report, set the `GTEST_OUTPUT` environment variable or the -`--gtest_output` flag to the string `"xml:_path_to_output_file_"`, which will -create the file at the given location. You can also just use the string -`"xml"`, in which case the output can be found in the `test_detail.xml` file in -the current directory. +`--gtest_output` flag to the string `"xml:path_to_output_file"`, which will +create the file at the given location. You can also just use the string `"xml"`, +in which case the output can be found in the `test_detail.xml` file in the +current directory. If you specify a directory (for example, `"xml:output/directory/"` on Linux or -`"xml:output\directory\"` on Windows), Google Test will create the XML file in +`"xml:output\directory\"` on Windows), googletest will create the XML file in that directory, named after the test executable (e.g. `foo_test.xml` for test program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left -over from a previous run), Google Test will pick a different name (e.g. +over from a previous run), googletest will pick a different name (e.g. `foo_test_1.xml`) to avoid overwriting it. -The report uses the format described here. It is based on the -`junitreport` Ant task and can be parsed by popular continuous build -systems like [Hudson](https://hudson.dev.java.net/). Since that format -was originally intended for Java, a little interpretation is required -to make it apply to Google Test tests, as shown here: -``` +The report is based on the `junitreport` Ant task. Since that format was +originally intended for Java, a little interpretation is required to make it +apply to googletest tests, as shown here: + +```xml - + @@ -2019,13 +2253,13 @@ to make it apply to Google Test tests, as shown here: ``` - * The root `` element corresponds to the entire test program. - * `` elements correspond to Google Test test cases. - * `` elements correspond to Google Test test functions. +* The root `` element corresponds to the entire test program. +* `` elements correspond to googletest test cases. +* `` elements correspond to googletest test functions. For instance, the following program -``` +```c++ TEST(MathTest, Addition) { ... } TEST(MathTest, Subtraction) { ... } TEST(LogicTest, NonContradiction) { ... } @@ -2033,19 +2267,19 @@ TEST(LogicTest, NonContradiction) { ... } could generate this report: -``` +```xml - - - - - + + + + ... + ... - + - - + + @@ -2053,18 +2287,26 @@ could generate this report: Things to note: - * The `tests` attribute of a `` or `` element tells how many test functions the Google Test program or test case contains, while the `failures` attribute tells how many of them failed. - * The `time` attribute expresses the duration of the test, test case, or entire test program in milliseconds. - * Each `` element corresponds to a single failed Google Test assertion. - * Some JUnit concepts don't apply to Google Test, yet we have to conform to the DTD. Therefore you'll see some dummy elements and attributes in the report. You can safely ignore these parts. +* The `tests` attribute of a `` or `` element tells how + many test functions the googletest program or test case contains, while the + `failures` attribute tells how many of them failed. + +* The `time` attribute expresses the duration of the test, test case, or + entire test program in seconds. + +* The `timestamp` attribute records the local date and time of the test + execution. -_Availability:_ Linux, Windows, Mac. +* Each `` element corresponds to a single failed googletest + assertion. -#### Generating an JSON Report {#JsonReport} +**Availability**: Linux, Windows, Mac. + +#### Generating an JSON Report -gUnit can also emit a JSON report as an alternative format to XML. To generate -the JSON report, set the `GUNIT_OUTPUT` environment variable or the -`--gunit_output` flag to the string `"json:path_to_output_file"`, which will +googletest can also emit a JSON report as an alternative format to XML. To +generate the JSON report, set the `GTEST_OUTPUT` environment variable or the +`--gtest_output` flag to the string `"json:path_to_output_file"`, which will create the file at the given location. You can also just use the string `"json"`, in which case the output can be found in the `test_detail.json` file in the current directory. @@ -2139,8 +2381,8 @@ The report format conforms to the following JSON Schema: } ``` -The report uses the format that conforms to the following Proto3 using the -[JSON encoding](https://developers.google.com/protocol-buffers/docs/proto3#json): +The report uses the format that conforms to the following Proto3 using the [JSON +encoding](https://developers.google.com/protocol-buffers/docs/proto3#json): ```proto syntax = "proto3"; @@ -2261,156 +2503,34 @@ IMPORTANT: The exact format of the JSON document is subject to change. **Availability**: Linux, Windows, Mac. -## Controlling How Failures Are Reported ## +### Controlling How Failures Are Reported -### Turning Assertion Failures into Break-Points ### +#### Turning Assertion Failures into Break-Points When running test programs under a debugger, it's very convenient if the debugger can catch an assertion failure and automatically drop into interactive -mode. Google Test's _break-on-failure_ mode supports this behavior. +mode. googletest's *break-on-failure* mode supports this behavior. To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value other than `0` . Alternatively, you can use the `--gtest_break_on_failure` command line flag. -_Availability:_ Linux, Windows, Mac. - -### Disabling Catching Test-Thrown Exceptions ### - -Google Test can be used either with or without exceptions enabled. If -a test throws a C++ exception or (on Windows) a structured exception -(SEH), by default Google Test catches it, reports it as a test -failure, and continues with the next test method. This maximizes the -coverage of a test run. Also, on Windows an uncaught exception will -cause a pop-up window, so catching the exceptions allows you to run -the tests automatically. - -When debugging the test failures, however, you may instead want the -exceptions to be handled by the debugger, such that you can examine -the call stack when an exception is thrown. To achieve that, set the -`GTEST_CATCH_EXCEPTIONS` environment variable to `0`, or use the -`--gtest_catch_exceptions=0` flag when running the tests. - **Availability**: Linux, Windows, Mac. -### Letting Another Testing Framework Drive ### - -If you work on a project that has already been using another testing -framework and is not ready to completely switch to Google Test yet, -you can get much of Google Test's benefit by using its assertions in -your existing tests. Just change your `main()` function to look -like: - -``` -#include "gtest/gtest.h" - -int main(int argc, char** argv) { - ::testing::GTEST_FLAG(throw_on_failure) = true; - // Important: Google Test must be initialized. - ::testing::InitGoogleTest(&argc, argv); - - ... whatever your existing testing framework requires ... -} -``` - -With that, you can use Google Test assertions in addition to the -native assertions your testing framework provides, for example: - -``` -void TestFooDoesBar() { - Foo foo; - EXPECT_LE(foo.Bar(1), 100); // A Google Test assertion. - CPPUNIT_ASSERT(foo.IsEmpty()); // A native assertion. -} -``` - -If a Google Test assertion fails, it will print an error message and -throw an exception, which will be treated as a failure by your host -testing framework. If you compile your code with exceptions disabled, -a failed Google Test assertion will instead exit your program with a -non-zero code, which will also signal a test failure to your test -runner. - -If you don't write `::testing::GTEST_FLAG(throw_on_failure) = true;` in -your `main()`, you can alternatively enable this feature by specifying -the `--gtest_throw_on_failure` flag on the command-line or setting the -`GTEST_THROW_ON_FAILURE` environment variable to a non-zero value. - -Death tests are _not_ supported when other test framework is used to organize tests. - -_Availability:_ Linux, Windows, Mac; since v1.3.0. - -## Distributing Test Functions to Multiple Machines ## - -If you have more than one machine you can use to run a test program, -you might want to run the test functions in parallel and get the -result faster. We call this technique _sharding_, where each machine -is called a _shard_. - -Google Test is compatible with test sharding. To take advantage of -this feature, your test runner (not part of Google Test) needs to do -the following: +#### Disabling Catching Test-Thrown Exceptions - 1. Allocate a number of machines (shards) to run the tests. - 1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total number of shards. It must be the same for all shards. - 1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index of the shard. Different shards must be assigned different indices, which must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. - 1. Run the same test program on all shards. When Google Test sees the above two environment variables, it will select a subset of the test functions to run. Across all shards, each test function in the program will be run exactly once. - 1. Wait for all shards to finish, then collect and report the results. +googletest can be used either with or without exceptions enabled. If a test +throws a C++ exception or (on Windows) a structured exception (SEH), by default +googletest catches it, reports it as a test failure, and continues with the next +test method. This maximizes the coverage of a test run. Also, on Windows an +uncaught exception will cause a pop-up window, so catching the exceptions allows +you to run the tests automatically. -Your project may have tests that were written without Google Test and -thus don't understand this protocol. In order for your test runner to -figure out which test supports sharding, it can set the environment -variable `GTEST_SHARD_STATUS_FILE` to a non-existent file path. If a -test program supports sharding, it will create this file to -acknowledge the fact (the actual contents of the file are not -important at this time; although we may stick some useful information -in it in the future.); otherwise it will not create it. +When debugging the test failures, however, you may instead want the exceptions +to be handled by the debugger, such that you can examine the call stack when an +exception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS` +environment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when +running the tests. -Here's an example to make it clear. Suppose you have a test program -`foo_test` that contains the following 5 test functions: -``` -TEST(A, V) -TEST(A, W) -TEST(B, X) -TEST(B, Y) -TEST(B, Z) -``` -and you have 3 machines at your disposal. To run the test functions in -parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and -set `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. -Then you would run the same `foo_test` on each machine. - -Google Test reserves the right to change how the work is distributed -across the shards, but here's one possible scenario: - - * Machine #0 runs `A.V` and `B.X`. - * Machine #1 runs `A.W` and `B.Y`. - * Machine #2 runs `B.Z`. - -_Availability:_ Linux, Windows, Mac; since version 1.3.0. - -# Fusing Google Test Source Files # - -Google Test's implementation consists of ~30 files (excluding its own -tests). Sometimes you may want them to be packaged up in two files (a -`.h` and a `.cc`) instead, such that you can easily copy them to a new -machine and start hacking there. For this we provide an experimental -Python script `fuse_gtest_files.py` in the `scripts/` directory (since release 1.3.0). -Assuming you have Python 2.4 or above installed on your machine, just -go to that directory and run -``` -python fuse_gtest_files.py OUTPUT_DIR -``` - -and you should see an `OUTPUT_DIR` directory being created with files -`gtest/gtest.h` and `gtest/gtest-all.cc` in it. These files contain -everything you need to use Google Test. Just copy them to anywhere -you want and you are ready to write tests. You can use the -[scripts/test/Makefile](../scripts/test/Makefile) -file as an example on how to compile your tests against them. - -# Where to Go from Here # +**Availability**: Linux, Windows, Mac. -Congratulations! You've now learned more advanced Google Test tools and are -ready to tackle more complex testing tasks. If you want to dive even deeper, you -can read the [Frequently-Asked Questions](faq.md). diff --git a/googletest/docs/faq.md b/googletest/docs/faq.md index 1e2c341..dad2836 100644 --- a/googletest/docs/faq.md +++ b/googletest/docs/faq.md @@ -1,337 +1,203 @@ +# Googletest FAQ -If you cannot find the answer to your question here, and you have read -[Primer](primer.md) and [AdvancedGuide](advanced.md), send it to -googletestframework@googlegroups.com. +## Why should test case names and test names not contain underscore? -## Why should I use Google Test instead of my favorite C++ testing framework? ## +Underscore (`_`) is special, as C++ reserves the following to be used by the +compiler and the standard library: -First, let us say clearly that we don't want to get into the debate of -which C++ testing framework is **the best**. There exist many fine -frameworks for writing C++ tests, and we have tremendous respect for -the developers and users of them. We don't think there is (or will -be) a single best framework - you have to pick the right tool for the -particular task you are tackling. +1. any identifier that starts with an `_` followed by an upper-case letter, and +1. any identifier that contains two consecutive underscores (i.e. `__`) + *anywhere* in its name. -We created Google Test because we couldn't find the right combination -of features and conveniences in an existing framework to satisfy _our_ -needs. The following is a list of things that _we_ like about Google -Test. We don't claim them to be unique to Google Test - rather, the -combination of them makes Google Test the choice for us. We hope this -list can help you decide whether it is for you too. - - * Google Test is designed to be portable: it doesn't require exceptions or RTTI; it works around various bugs in various compilers and environments; etc. As a result, it works on Linux, Mac OS X, Windows and several embedded operating systems. - * Nonfatal assertions (`EXPECT_*`) have proven to be great time savers, as they allow a test to report multiple failures in a single edit-compile-test cycle. - * It's easy to write assertions that generate informative messages: you just use the stream syntax to append any additional information, e.g. `ASSERT_EQ(5, Foo(i)) << " where i = " << i;`. It doesn't require a new set of macros or special functions. - * Google Test automatically detects your tests and doesn't require you to enumerate them in order to run them. - * Death tests are pretty handy for ensuring that your asserts in production code are triggered by the right conditions. - * `SCOPED_TRACE` helps you understand the context of an assertion failure when it comes from inside a sub-routine or loop. - * You can decide which tests to run using name patterns. This saves time when you want to quickly reproduce a test failure. - * Google Test can generate XML test result reports that can be parsed by popular continuous build system like Hudson. - * Simple things are easy in Google Test, while hard things are possible: in addition to advanced features like [global test environments](advanced.md#global-set-up-and-tear-down) and tests parameterized by [values](advanced.md#value-parameterized-tests) or [types](docs/advanced.md#typed-tests), Google Test supports various ways for the user to extend the framework -- if Google Test doesn't do something out of the box, chances are that a user can implement the feature using Google Test's public API, without changing Google Test itself. In particular, you can: - * expand your testing vocabulary by defining [custom predicates](advanced.md#predicate-assertions-for-better-error-messages), - * teach Google Test how to [print your types](advanced.md#teaching-google-test-how-to-print-your-values), - * define your own testing macros or utilities and verify them using Google Test's [Service Provider Interface](advanced.md#catching-failures), and - * reflect on the test cases or change the test output format by intercepting the [test events](advanced.md#extending-google-test-by-handling-test-events). - -## I'm getting warnings when compiling Google Test. Would you fix them? ## - -We strive to minimize compiler warnings Google Test generates. Before releasing a new version, we test to make sure that it doesn't generate warnings when compiled using its CMake script on Windows, Linux, and Mac OS. - -Unfortunately, this doesn't mean you are guaranteed to see no warnings when compiling Google Test in your environment: - - * You may be using a different compiler as we use, or a different version of the same compiler. We cannot possibly test for all compilers. - * You may be compiling on a different platform as we do. - * Your project may be using different compiler flags as we do. - -It is not always possible to make Google Test warning-free for everyone. Or, it may not be desirable if the warning is rarely enabled and fixing the violations makes the code more complex. - -If you see warnings when compiling Google Test, we suggest that you use the `-isystem` flag (assuming your are using GCC) to mark Google Test headers as system headers. That'll suppress warnings from Google Test headers. - -## Why should not test case names and test names contain underscore? ## - -Underscore (`_`) is special, as C++ reserves the following to be used by -the compiler and the standard library: - - 1. any identifier that starts with an `_` followed by an upper-case letter, and - 1. any identifier that contains two consecutive underscores (i.e. `__`) _anywhere_ in its name. - -User code is _prohibited_ from using such identifiers. +User code is *prohibited* from using such identifiers. Now let's look at what this means for `TEST` and `TEST_F`. Currently `TEST(TestCaseName, TestName)` generates a class named -`TestCaseName_TestName_Test`. What happens if `TestCaseName` or `TestName` +`TestCaseName_TestName_Test`. What happens if `TestCaseName` or `TestName` contains `_`? - 1. If `TestCaseName` starts with an `_` followed by an upper-case letter (say, `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus invalid. - 1. If `TestCaseName` ends with an `_` (say, `Foo_`), we get `Foo__TestName_Test`, which is invalid. - 1. If `TestName` starts with an `_` (say, `_Bar`), we get `TestCaseName__Bar_Test`, which is invalid. - 1. If `TestName` ends with an `_` (say, `Bar_`), we get `TestCaseName_Bar__Test`, which is invalid. +1. If `TestCaseName` starts with an `_` followed by an upper-case letter (say, + `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus + invalid. +1. If `TestCaseName` ends with an `_` (say, `Foo_`), we get + `Foo__TestName_Test`, which is invalid. +1. If `TestName` starts with an `_` (say, `_Bar`), we get + `TestCaseName__Bar_Test`, which is invalid. +1. If `TestName` ends with an `_` (say, `Bar_`), we get + `TestCaseName_Bar__Test`, which is invalid. + +So clearly `TestCaseName` and `TestName` cannot start or end with `_` (Actually, +`TestCaseName` can start with `_` -- as long as the `_` isn't followed by an +upper-case letter. But that's getting complicated. So for simplicity we just say +that it cannot start with `_`.). -So clearly `TestCaseName` and `TestName` cannot start or end with `_` -(Actually, `TestCaseName` can start with `_` -- as long as the `_` isn't -followed by an upper-case letter. But that's getting complicated. So -for simplicity we just say that it cannot start with `_`.). +It may seem fine for `TestCaseName` and `TestName` to contain `_` in the middle. +However, consider this: -It may seem fine for `TestCaseName` and `TestName` to contain `_` in the -middle. However, consider this: ```c++ TEST(Time, Flies_Like_An_Arrow) { ... } TEST(Time_Flies, Like_An_Arrow) { ... } ``` Now, the two `TEST`s will both generate the same class -(`Time_Files_Like_An_Arrow_Test`). That's not good. - -So for simplicity, we just ask the users to avoid `_` in `TestCaseName` -and `TestName`. The rule is more constraining than necessary, but it's -simple and easy to remember. It also gives Google Test some wiggle -room in case its implementation needs to change in the future. - -If you violate the rule, there may not be immediately consequences, -but your test may (just may) break with a new compiler (or a new -version of the compiler you are using) or with a new version of Google -Test. Therefore it's best to follow the rule. - -## Why is it not recommended to install a pre-compiled copy of Google Test (for example, into /usr/local)? ## - -In the early days, we said that you could install -compiled Google Test libraries on `*`nix systems using `make install`. -Then every user of your machine can write tests without -recompiling Google Test. - -This seemed like a good idea, but it has a -got-cha: every user needs to compile their tests using the _same_ compiler -flags used to compile the installed Google Test libraries; otherwise -they may run into undefined behaviors (i.e. the tests can behave -strangely and may even crash for no obvious reasons). - -Why? Because C++ has this thing called the One-Definition Rule: if -two C++ source files contain different definitions of the same -class/function/variable, and you link them together, you violate the -rule. The linker may or may not catch the error (in many cases it's -not required by the C++ standard to catch the violation). If it -doesn't, you get strange run-time behaviors that are unexpected and -hard to debug. - -If you compile Google Test and your test code using different compiler -flags, they may see different definitions of the same -class/function/variable (e.g. due to the use of `#if` in Google Test). -Therefore, for your sanity, we recommend to avoid installing pre-compiled -Google Test libraries. Instead, each project should compile -Google Test itself such that it can be sure that the same flags are -used for both Google Test and the tests. - -## How do I generate 64-bit binaries on Windows (using Visual Studio 2008)? ## - -(Answered by Trevor Robinson) - -Load the supplied Visual Studio solution file, either `msvc\gtest-md.sln` or -`msvc\gtest.sln`. Go through the migration wizard to migrate the -solution and project files to Visual Studio 2008. Select -`Configuration Manager...` from the `Build` menu. Select `` from -the `Active solution platform` dropdown. Select `x64` from the new -platform dropdown, leave `Copy settings from` set to `Win32` and -`Create new project platforms` checked, then click `OK`. You now have -`Win32` and `x64` platform configurations, selectable from the -`Standard` toolbar, which allow you to toggle between building 32-bit or -64-bit binaries (or both at once using Batch Build). - -In order to prevent build output files from overwriting one another, -you'll need to change the `Intermediate Directory` settings for the -newly created platform configuration across all the projects. To do -this, multi-select (e.g. using shift-click) all projects (but not the -solution) in the `Solution Explorer`. Right-click one of them and -select `Properties`. In the left pane, select `Configuration Properties`, -and from the `Configuration` dropdown, select `All Configurations`. -Make sure the selected platform is `x64`. For the -`Intermediate Directory` setting, change the value from -`$(PlatformName)\$(ConfigurationName)` to -`$(OutDir)\$(ProjectName)`. Click `OK` and then build the -solution. When the build is complete, the 64-bit binaries will be in -the `msvc\x64\Debug` directory. - -## Can I use Google Test on MinGW? ## - -We haven't tested this ourselves, but Per Abrahamsen reported that he -was able to compile and install Google Test successfully when using -MinGW from Cygwin. You'll need to configure it with: - -`PATH/TO/configure CC="gcc -mno-cygwin" CXX="g++ -mno-cygwin"` - -You should be able to replace the `-mno-cygwin` option with direct links -to the real MinGW binaries, but we haven't tried that. - -Caveats: - - * There are many warnings when compiling. - * `make check` will produce some errors as not all tests for Google Test itself are compatible with MinGW. - -We also have reports on successful cross compilation of Google Test -MinGW binaries on Linux using -[these instructions](http://wiki.wxwidgets.org/Cross-Compiling_Under_Linux#Cross-compiling_under_Linux_for_MS_Windows) -on the WxWidgets site. - -Please contact `googletestframework@googlegroups.com` if you are -interested in improving the support for MinGW. - -## Why does Google Test support EXPECT\_EQ(NULL, ptr) and ASSERT\_EQ(NULL, ptr) but not EXPECT\_NE(NULL, ptr) and ASSERT\_NE(NULL, ptr)? ## - -Due to some peculiarity of C++, it requires some non-trivial template -meta programming tricks to support using `NULL` as an argument of the -`EXPECT_XX()` and `ASSERT_XX()` macros. Therefore we only do it where -it's most needed (otherwise we make the implementation of Google Test -harder to maintain and more error-prone than necessary). - -The `EXPECT_EQ()` macro takes the _expected_ value as its first -argument and the _actual_ value as the second. It's reasonable that -someone wants to write `EXPECT_EQ(NULL, some_expression)`, and this -indeed was requested several times. Therefore we implemented it. - -The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the -assertion fails, you already know that `ptr` must be `NULL`, so it -doesn't add any information to print ptr in this case. That means -`EXPECT_TRUE(ptr != NULL)` works just as well. - -If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll -have to support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, -we don't have a convention on the order of the two arguments for -`EXPECT_NE`. This means using the template meta programming tricks -twice in the implementation, making it even harder to understand and -maintain. We believe the benefit doesn't justify the cost. - -Finally, with the growth of Google Mock's [matcher](../../googlemock/docs/CookBook.md#using-matchers-in-google-test-assertions) library, we are -encouraging people to use the unified `EXPECT_THAT(value, matcher)` -syntax more often in tests. One significant advantage of the matcher -approach is that matchers can be easily combined to form new matchers, -while the `EXPECT_NE`, etc, macros cannot be easily -combined. Therefore we want to invest more in the matchers than in the +(`Time_Flies_Like_An_Arrow_Test`). That's not good. + +So for simplicity, we just ask the users to avoid `_` in `TestCaseName` and +`TestName`. The rule is more constraining than necessary, but it's simple and +easy to remember. It also gives googletest some wiggle room in case its +implementation needs to change in the future. + +If you violate the rule, there may not be immediate consequences, but your test +may (just may) break with a new compiler (or a new version of the compiler you +are using) or with a new version of googletest. Therefore it's best to follow +the rule. + +## Why does googletest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`? + +First of all you can use `EXPECT_NE(nullptr, ptr)` and `ASSERT_NE(nullptr, +ptr)`. This is the preferred syntax in the style guide because nullptr does not +have the type problems that NULL does. Which is why NULL does not work. + +Due to some peculiarity of C++, it requires some non-trivial template meta +programming tricks to support using `NULL` as an argument of the `EXPECT_XX()` +and `ASSERT_XX()` macros. Therefore we only do it where it's most needed +(otherwise we make the implementation of googletest harder to maintain and more +error-prone than necessary). + +The `EXPECT_EQ()` macro takes the *expected* value as its first argument and the +*actual* value as the second. It's reasonable that someone wants to write +`EXPECT_EQ(NULL, some_expression)`, and this indeed was requested several times. +Therefore we implemented it. + +The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the assertion +fails, you already know that `ptr` must be `NULL`, so it doesn't add any +information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)` +works just as well. + +If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll have to +support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, we don't have a +convention on the order of the two arguments for `EXPECT_NE`. This means using +the template meta programming tricks twice in the implementation, making it even +harder to understand and maintain. We believe the benefit doesn't justify the +cost. + +Finally, with the growth of the gMock matcher library, we are encouraging people +to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One +significant advantage of the matcher approach is that matchers can be easily +combined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be +easily combined. Therefore we want to invest more in the matchers than in the `EXPECT_XX()` macros. -## Does Google Test support running tests in parallel? ## - -Test runners tend to be tightly coupled with the build/test -environment, and Google Test doesn't try to solve the problem of -running tests in parallel. Instead, we tried to make Google Test work -nicely with test runners. For example, Google Test's XML report -contains the time spent on each test, and its `gtest_list_tests` and -`gtest_filter` flags can be used for splitting the execution of test -methods into multiple processes. These functionalities can help the -test runner run the tests in parallel. +## I need to test that different implementations of an interface satisfy some common requirements. Should I use typed tests or value-parameterized tests? -## Why don't Google Test run the tests in different threads to speed things up? ## +For testing various implementations of the same interface, either typed tests or +value-parameterized tests can get it done. It's really up to you the user to +decide which is more convenient for you, depending on your particular case. Some +rough guidelines: -It's difficult to write thread-safe code. Most tests are not written -with thread-safety in mind, and thus may not work correctly in a -multi-threaded setting. +* Typed tests can be easier to write if instances of the different + implementations can be created the same way, modulo the type. For example, + if all these implementations have a public default constructor (such that + you can write `new TypeParam`), or if their factory functions have the same + form (e.g. `CreateInstance()`). +* Value-parameterized tests can be easier to write if you need different code + patterns to create different implementations' instances, e.g. `new Foo` vs + `new Bar(5)`. To accommodate for the differences, you can write factory + function wrappers and pass these function pointers to the tests as their + parameters. +* When a typed test fails, the output includes the name of the type, which can + help you quickly identify which implementation is wrong. Value-parameterized + tests cannot do this, so there you'll have to look at the iteration number + to know which implementation the failure is from, which is less direct. +* If you make a mistake writing a typed test, the compiler errors can be + harder to digest, as the code is templatized. +* When using typed tests, you need to make sure you are testing against the + interface type, not the concrete types (in other words, you want to make + sure `implicit_cast(my_concrete_impl)` works, not just that + `my_concrete_impl` works). It's less likely to make mistakes in this area + when using value-parameterized tests. -If you think about it, it's already hard to make your code work when -you know what other threads are doing. It's much harder, and -sometimes even impossible, to make your code work when you don't know -what other threads are doing (remember that test methods can be added, -deleted, or modified after your test was written). If you want to run -the tests in parallel, you'd better run them in different processes. +I hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give +both approaches a try. Practice is a much better way to grasp the subtle +differences between the two tools. Once you have some concrete experience, you +can much more easily decide which one to use the next time. -## Why aren't Google Test assertions implemented using exceptions? ## +## My death tests became very slow - what happened? -Our original motivation was to be able to use Google Test in projects -that disable exceptions. Later we realized some additional benefits -of this approach: - - 1. Throwing in a destructor is undefined behavior in C++. Not using exceptions means Google Test's assertions are safe to use in destructors. - 1. The `EXPECT_*` family of macros will continue even after a failure, allowing multiple failures in a `TEST` to be reported in a single run. This is a popular feature, as in C++ the edit-compile-test cycle is usually quite long and being able to fixing more than one thing at a time is a blessing. - 1. If assertions are implemented using exceptions, a test may falsely ignore a failure if it's caught by user code: -```c++ -try { ... ASSERT_TRUE(...) ... } -catch (...) { ... } -``` -The above code will pass even if the `ASSERT_TRUE` throws. While it's unlikely for someone to write this in a test, it's possible to run into this pattern when you write assertions in callbacks that are called by the code under test. +In August 2008 we had to switch the default death test style from `fast` to +`threadsafe`, as the former is no longer safe now that threaded logging is the +default. This caused many death tests to slow down. Unfortunately this change +was necessary. -The downside of not using exceptions is that `ASSERT_*` (implemented -using `return`) will only abort the current function, not the current -`TEST`. +Please read [Fixing Failing Death Tests](death_test_styles.md) for what you can +do. -## Why do we use two different macros for tests with and without fixtures? ## +## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help! -Unfortunately, C++'s macro system doesn't allow us to use the same -macro for both cases. One possibility is to provide only one macro -for tests with fixtures, and require the user to define an empty -fixture sometimes: +**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated* +now. Please use `EqualsProto`, etc instead. -```c++ -class FooTest : public ::testing::Test {}; +`ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and +are now less tolerant on invalid protocol buffer definitions. In particular, if +you have a `foo.proto` that doesn't fully qualify the type of a protocol message +it references (e.g. `message` where it should be `message`), you +will now get run-time errors like: -TEST_F(FooTest, DoesThis) { ... } ``` -or -```c++ -typedef ::testing::Test FooTest; - -TEST_F(FooTest, DoesThat) { ... } +... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto": +... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined. ``` -Yet, many people think this is one line too many. :-) Our goal was to -make it really easy to write tests, so we tried to make simple tests -trivial to create. That means using a separate macro for such tests. +If you see this, your `.proto` file is broken and needs to be fixed by making +the types fully qualified. The new definition of `ProtocolMessageEquals` and +`ProtocolMessageEquiv` just happen to reveal your bug. -We think neither approach is ideal, yet either of them is reasonable. -In the end, it probably doesn't matter much either way. +## My death test modifies some state, but the change seems lost after the death test finishes. Why? -## Why don't we use structs as test fixtures? ## +Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the +expected crash won't kill the test program (i.e. the parent process). As a +result, any in-memory side effects they incur are observable in their respective +sub-processes, but not in the parent process. You can think of them as running +in a parallel universe, more or less. -We like to use structs only when representing passive data. This -distinction between structs and classes is good for documenting the -intent of the code's author. Since test fixtures have logic like -`SetUp()` and `TearDown()`, they are better defined as classes. +In particular, if you use [gMock](http://go/gmock) and the death test statement +invokes some mock methods, the parent process will think the calls have never +occurred. Therefore, you may want to move your `EXPECT_CALL` statements inside +the `EXPECT_DEATH` macro. -## Why are death tests implemented as assertions instead of using a test runner? ## +## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug? -Our goal was to make death tests as convenient for a user as C++ -possibly allows. In particular: +Actually, the bug is in `htonl()`. - * The runner-style requires to split the information into two pieces: the definition of the death test itself, and the specification for the runner on how to run the death test and what to expect. The death test would be written in C++, while the runner spec may or may not be. A user needs to carefully keep the two in sync. `ASSERT_DEATH(statement, expected_message)` specifies all necessary information in one place, in one language, without boilerplate code. It is very declarative. - * `ASSERT_DEATH` has a similar syntax and error-reporting semantics as other Google Test assertions, and thus is easy to learn. - * `ASSERT_DEATH` can be mixed with other assertions and other logic at your will. You are not limited to one death test per test method. For example, you can write something like: -```c++ - if (FooCondition()) { - ASSERT_DEATH(Bar(), "blah"); - } else { - ASSERT_EQ(5, Bar()); - } -``` -If you prefer one death test per test method, you can write your tests in that style too, but we don't want to impose that on the users. The fewer artificial limitations the better. - * `ASSERT_DEATH` can reference local variables in the current function, and you can decide how many death tests you want based on run-time information. For example, -```c++ - const int count = GetCount(); // Only known at run time. - for (int i = 1; i <= count; i++) { - ASSERT_DEATH({ - double* buffer = new double[i]; - ... initializes buffer ... - Foo(buffer, i) - }, "blah blah"); - } -``` -The runner-based approach tends to be more static and less flexible, or requires more user effort to get this kind of flexibility. +According to `'man htonl'`, `htonl()` is a *function*, which means it's valid to +use `htonl` as a function pointer. However, in opt mode `htonl()` is defined as +a *macro*, which breaks this usage. -Another interesting thing about `ASSERT_DEATH` is that it calls `fork()` -to create a child process to run the death test. This is lightening -fast, as `fork()` uses copy-on-write pages and incurs almost zero -overhead, and the child process starts from the user-supplied -statement directly, skipping all global and local initialization and -any code leading to the given statement. If you launch the child -process from scratch, it can take seconds just to load everything and -start running if the test links to many libraries dynamically. +Worse, the macro definition of `htonl()` uses a `gcc` extension and is *not* +standard C++. That hacky implementation has some ad hoc limitations. In +particular, it prevents you from writing `Foo()`, where `Foo` +is a template that has an integral argument. -## My death test modifies some state, but the change seems lost after the death test finishes. Why? ## +The implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a +template argument, and thus doesn't compile in opt mode when `a` contains a call +to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as +the solution must work with different compilers on various platforms. -Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the -expected crash won't kill the test program (i.e. the parent process). As a -result, any in-memory side effects they incur are observable in their -respective sub-processes, but not in the parent process. You can think of them -as running in a parallel universe, more or less. +`htonl()` has some other problems as described in `//util/endian/endian.h`, +which defines `ghtonl()` to replace it. `ghtonl()` does the same thing `htonl()` +does, only without its problems. We suggest you to use `ghtonl()` instead of +`htonl()`, both in your tests and production code. + +`//util/endian/endian.h` also defines `ghtons()`, which solves similar problems +in `htons()`. -## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? ## +Don't forget to add `//util/endian` to the list of dependencies in the `BUILD` +file wherever `ghtonl()` and `ghtons()` are used. The library consists of a +single header file and will not bloat your binary. + +## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? If your class has a static data member: @@ -343,23 +209,18 @@ class Foo { }; ``` -You also need to define it _outside_ of the class body in `foo.cc`: +You also need to define it *outside* of the class body in `foo.cc`: ```c++ const int Foo::kBar; // No initializer here. ``` Otherwise your code is **invalid C++**, and may break in unexpected ways. In -particular, using it in Google Test comparison assertions (`EXPECT_EQ`, etc) -will generate an "undefined reference" linker error. - -## I have an interface that has several implementations. Can I write a set of tests once and repeat them over all the implementations? ## - -Google Test doesn't yet have good support for this kind of tests, or -data-driven tests in general. We hope to be able to make improvements in this -area soon. +particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will +generate an "undefined reference" linker error. The fact that "it used to work" +doesn't mean it's valid. It just means that you were lucky. :-) -## Can I derive a test fixture from another? ## +## Can I derive a test fixture from another? Yes. @@ -369,33 +230,35 @@ cases may want to use the same or slightly different fixtures. For example, you may want to make sure that all of a GUI library's test cases don't leak important system resources like fonts and brushes. -In Google Test, you share a fixture among test cases by putting the shared -logic in a base test fixture, then deriving from that base a separate fixture -for each test case that wants to use this common logic. You then use `TEST_F()` -to write tests using each derived fixture. +In googletest, you share a fixture among test cases by putting the shared logic +in a base test fixture, then deriving from that base a separate fixture for each +test case that wants to use this common logic. You then use `TEST_F()` to write +tests using each derived fixture. Typically, your code looks like this: ```c++ // Defines a base test fixture. class BaseTest : public ::testing::Test { - protected: - ... + protected: + ... }; // Derives a fixture FooTest from BaseTest. class FooTest : public BaseTest { - protected: - virtual void SetUp() { - BaseTest::SetUp(); // Sets up the base fixture first. - ... additional set-up work ... - } - virtual void TearDown() { - ... clean-up work for FooTest ... - BaseTest::TearDown(); // Remember to tear down the base fixture - // after cleaning up FooTest! - } - ... functions and variables for FooTest ... + protected: + void SetUp() override { + BaseTest::SetUp(); // Sets up the base fixture first. + ... additional set-up work ... + } + + void TearDown() override { + ... clean-up work for FooTest ... + BaseTest::TearDown(); // Remember to tear down the base fixture + // after cleaning up FooTest! + } + + ... functions and variables for FooTest ... }; // Tests that use the fixture FooTest. @@ -406,32 +269,35 @@ TEST_F(FooTest, Baz) { ... } ``` If necessary, you can continue to derive test fixtures from a derived fixture. -Google Test has no limit on how deep the hierarchy can be. +googletest has no limit on how deep the hierarchy can be. -For a complete example using derived test fixtures, see -[sample5](../samples/sample5_unittest.cc). +For a complete example using derived test fixtures, see [googletest +sample](https://github.com/google/googletest/blob/master/googletest/samples/sample5_unittest.cc) -## My compiler complains "void value not ignored as it ought to be." What does this mean? ## +## My compiler complains "void value not ignored as it ought to be." What does this mean? You're probably using an `ASSERT_*()` in a function that doesn't return `void`. -`ASSERT_*()` can only be used in `void` functions. +`ASSERT_*()` can only be used in `void` functions, due to exceptions being +disabled by our build system. Please see more details +[here](advanced.md#assertion-placement). -## My death test hangs (or seg-faults). How do I fix it? ## +## My death test hangs (or seg-faults). How do I fix it? -In Google Test, death tests are run in a child process and the way they work is +In googletest, death tests are run in a child process and the way they work is delicate. To write death tests you really need to understand how they work. -Please make sure you have read this. +Please make sure you have read [this](advanced.md#how-it-works). In particular, death tests don't like having multiple threads in the parent -process. So the first thing you can try is to eliminate creating threads -outside of `EXPECT_DEATH()`. +process. So the first thing you can try is to eliminate creating threads outside +of `EXPECT_DEATH()`. For example, you may want to use [mocks](http://go/gmock) +or fake objects instead of real ones in your tests. Sometimes this is impossible as some library you must use may be creating threads before `main()` is even reached. In this case, you can try to minimize the chance of conflicts by either moving as many activities as possible inside `EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or -leaving as few things as possible in it. Also, you can try to set the death -test style to `"threadsafe"`, which is safer but slower, and see if it helps. +leaving as few things as possible in it. Also, you can try to set the death test +style to `"threadsafe"`, which is safer but slower, and see if it helps. If you go with thread-safe death tests, remember that they rerun the test program from the beginning in the child process. Therefore make sure your @@ -441,28 +307,52 @@ In the end, this boils down to good concurrent programming. You have to make sure that there is no race conditions or dead locks in your program. No silver bullet - sorry! -## Should I use the constructor/destructor of the test fixture or the set-up/tear-down function? ## +## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? -The first thing to remember is that Google Test does not reuse the -same test fixture object across multiple tests. For each `TEST_F`, -Google Test will create a fresh test fixture object, _immediately_ -call `SetUp()`, run the test body, call `TearDown()`, and then -_immediately_ delete the test fixture object. +The first thing to remember is that googletest does **not** reuse the same test +fixture object across multiple tests. For each `TEST_F`, googletest will create +a **fresh** test fixture object, immediately call `SetUp()`, run the test body, +call `TearDown()`, and then delete the test fixture object. -When you need to write per-test set-up and tear-down logic, you have -the choice between using the test fixture constructor/destructor or -`SetUp()/TearDown()`. The former is usually preferred, as it has the -following benefits: +When you need to write per-test set-up and tear-down logic, you have the choice +between using the test fixture constructor/destructor or `SetUp()/TearDown()`. +The former is usually preferred, as it has the following benefits: - * By initializing a member variable in the constructor, we have the option to make it `const`, which helps prevent accidental changes to its value and makes the tests more obviously correct. - * In case we need to subclass the test fixture class, the subclass' constructor is guaranteed to call the base class' constructor first, and the subclass' destructor is guaranteed to call the base class' destructor afterward. With `SetUp()/TearDown()`, a subclass may make the mistake of forgetting to call the base class' `SetUp()/TearDown()` or call them at the wrong moment. +* By initializing a member variable in the constructor, we have the option to + make it `const`, which helps prevent accidental changes to its value and + makes the tests more obviously correct. +* In case we need to subclass the test fixture class, the subclass' + constructor is guaranteed to call the base class' constructor *first*, and + the subclass' destructor is guaranteed to call the base class' destructor + *afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of + forgetting to call the base class' `SetUp()/TearDown()` or call them at the + wrong time. You may still want to use `SetUp()/TearDown()` in the following rare cases: - * If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions. - * The assertion macros throw an exception when flag `--gtest_throw_on_failure` is specified. Therefore, you shouldn't use Google Test assertions in a destructor if you plan to run your tests with this flag. - * In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overridden in a derived class, you have to use `SetUp()/TearDown()`. -## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ## +* In the body of a constructor (or destructor), it's not possible to use the + `ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal + test failure that should prevent the test from running, it's necessary to + use a `CHECK` macro or to use `SetUp()` instead of a constructor. +* If the tear-down operation could throw an exception, you must use + `TearDown()` as opposed to the destructor, as throwing in a destructor leads + to undefined behavior and usually will kill your program right away. Note + that many standard libraries (like STL) may throw when exceptions are + enabled in the compiler. Therefore you should prefer `TearDown()` if you + want to write portable tests that work with or without exceptions. +* The googletest team is considering making the assertion macros throw on + platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux + client-side), which will eliminate the need for the user to propagate + failures from a subroutine to its caller. Therefore, you shouldn't use + googletest assertions in a destructor if your code could run on such a + platform. +* In a constructor or destructor, you cannot make a virtual function call on + this object. (You can call a method declared as virtual, but it will be + statically bound.) Therefore, if you need to call a method that will be + overridden in a derived class, you have to use `SetUp()/TearDown()`. + + +## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it? If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is overloaded or a template, the compiler will have trouble figuring out which @@ -480,6 +370,7 @@ For example, suppose you have bool IsPositive(int n) { return n > 0; } + bool IsPositive(double x) { return x > 0; } @@ -497,8 +388,8 @@ However, this will work: EXPECT_PRED1(static_cast(IsPositive), 5); ``` -(The stuff inside the angled brackets for the `static_cast` operator is the -type of the function pointer for the `int`-version of `IsPositive()`.) +(The stuff inside the angled brackets for the `static_cast` operator is the type +of the function pointer for the `int`-version of `IsPositive()`.) As another example, when you have a template function @@ -522,72 +413,76 @@ following won't compile: ASSERT_PRED2(GreaterThan, 5, 0); ``` - -as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, -which is one more than expected. The workaround is to wrap the predicate -function in parentheses: +as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, which +is one more than expected. The workaround is to wrap the predicate function in +parentheses: ```c++ ASSERT_PRED2((GreaterThan), 5, 0); ``` -## My compiler complains about "ignoring return value" when I call RUN\_ALL\_TESTS(). Why? ## +## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why? Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is, instead of ```c++ -return RUN_ALL_TESTS(); + return RUN_ALL_TESTS(); ``` they write ```c++ -RUN_ALL_TESTS(); + RUN_ALL_TESTS(); ``` -This is wrong and dangerous. A test runner needs to see the return value of -`RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()` -function ignores it, your test will be considered successful even if it has a -Google Test assertion failure. Very bad. +This is **wrong and dangerous**. The testing services needs to see the return +value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your +`main()` function ignores it, your test will be considered successful even if it +has a googletest assertion failure. Very bad. -To help the users avoid this dangerous bug, the implementation of -`RUN_ALL_TESTS()` causes gcc to raise this warning, when the return value is -ignored. If you see this warning, the fix is simple: just make sure its value -is used as the return value of `main()`. +We have decided to fix this (thanks to Michael Chastain for the idea). Now, your +code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with +`gcc`. If you do so, you'll get a compiler error. -## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? ## +If you see the compiler complaining about you ignoring the return value of +`RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the +return value of `main()`. + +But how could we introduce a change that breaks existing tests? Well, in this +case, the code was already broken in the first place, so we didn't break it. :-) + +## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? Due to a peculiarity of C++, in order to support the syntax for streaming messages to an `ASSERT_*`, e.g. ```c++ -ASSERT_EQ(1, Foo()) << "blah blah" << foo; + ASSERT_EQ(1, Foo()) << "blah blah" << foo; ``` we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and `ADD_FAILURE*`) in constructors and destructors. The workaround is to move the content of your constructor/destructor to a private void member function, or -switch to `EXPECT_*()` if that works. This section in the user's guide explains -it. +switch to `EXPECT_*()` if that works. This +[section](advanced.md#assertion-placement) in the user's guide explains it. -## My set-up function is not called. Why? ## +## My SetUp() function is not called. Why? -C++ is case-sensitive. It should be spelled as `SetUp()`. Did you -spell it as `Setup()`? +C++ is case-sensitive. Did you spell it as `Setup()`? Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and wonder why it's never called. -## How do I jump to the line of a failure in Emacs directly? ## +## How do I jump to the line of a failure in Emacs directly? + +googletest's failure message format is understood by Emacs and many other IDEs, +like acme and XCode. If a googletest message is in a compilation buffer in +Emacs, then it's clickable. -Google Test's failure message format is understood by Emacs and many other -IDEs, like acme and XCode. If a Google Test message is in a compilation buffer -in Emacs, then it's clickable. You can now hit `enter` on a message to jump to -the corresponding source code, or use `C-x `` to jump to the next failure. -## I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. ## +## I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. You don't have to. Instead of @@ -604,6 +499,7 @@ TEST_F(BarTest, Def) { ... } ``` you can simply `typedef` the test fixtures: + ```c++ typedef BaseTest FooTest; @@ -616,192 +512,47 @@ TEST_F(BarTest, Abc) { ... } TEST_F(BarTest, Def) { ... } ``` -## The Google Test output is buried in a whole bunch of log messages. What do I do? ## +## googletest output is buried in a whole bunch of LOG messages. What do I do? -The Google Test output is meant to be a concise and human-friendly report. If -your test generates textual output itself, it will mix with the Google Test +The googletest output is meant to be a concise and human-friendly report. If +your test generates textual output itself, it will mix with the googletest output, making it hard to read. However, there is an easy solution to this problem. -Since most log messages go to stderr, we decided to let Google Test output go -to stdout. This way, you can easily separate the two using redirection. For +Since `LOG` messages go to stderr, we decided to let googletest output go to +stdout. This way, you can easily separate the two using redirection. For example: -``` -./my_test > googletest_output.txt -``` - -## Why should I prefer test fixtures over global variables? ## - -There are several good reasons: - 1. It's likely your test needs to change the states of its global variables. This makes it difficult to keep side effects from escaping one test and contaminating others, making debugging difficult. By using fixtures, each test has a fresh set of variables that's different (but with the same names). Thus, tests are kept independent of each other. - 1. Global variables pollute the global namespace. - 1. Test fixtures can be reused via subclassing, which cannot be done easily with global variables. This is useful if many test cases have something in common. - -## How do I test private class members without writing FRIEND\_TEST()s? ## -You should try to write testable code, which means classes should be easily -tested from their public interface. One way to achieve this is the Pimpl idiom: -you move all private members of a class into a helper class, and make all -members of the helper class public. - -You have several other options that don't require using `FRIEND_TEST`: - * Write the tests as members of the fixture class: -```c++ -class Foo { - friend class FooTest; - ... -}; - -class FooTest : public ::testing::Test { - protected: - ... - void Test1() {...} // This accesses private members of class Foo. - void Test2() {...} // So does this one. -}; - -TEST_F(FooTest, Test1) { - Test1(); -} - -TEST_F(FooTest, Test2) { - Test2(); -} +```shell +$ ./my_test > gtest_output.txt ``` - * In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests: -```c++ -class Foo { - friend class FooTest; - ... -}; -class FooTest : public ::testing::Test { - protected: - ... - T1 get_private_member1(Foo* obj) { - return obj->private_member1_; - } -}; -TEST_F(FooTest, Test1) { - ... - get_private_member1(x) - ... -} -``` - * If the methods are declared **protected**, you can change their access level in a test-only subclass: -```c++ -class YourClass { - ... - protected: // protected access for testability. - int DoSomethingReturningInt(); - ... -}; - -// in the your_class_test.cc file: -class TestableYourClass : public YourClass { - ... - public: using YourClass::DoSomethingReturningInt; // changes access rights - ... -}; - -TEST_F(YourClassTest, DoSomethingTest) { - TestableYourClass obj; - assertEquals(expected_value, obj.DoSomethingReturningInt()); -} -``` - -## How do I test private class static members without writing FRIEND\_TEST()s? ## - -We find private static methods clutter the header file. They are -implementation details and ideally should be kept out of a .h. So often I make -them free functions instead. - -Instead of: -```c++ -// foo.h -class Foo { - ... - private: - static bool Func(int n); -}; - -// foo.cc -bool Foo::Func(int n) { ... } - -// foo_test.cc -EXPECT_TRUE(Foo::Func(12345)); -``` - -You probably should better write: -```c++ -// foo.h -class Foo { - ... -}; - -// foo.cc -namespace internal { - bool Func(int n) { ... } -} - -// foo_test.cc -namespace internal { - bool Func(int n); -} - -EXPECT_TRUE(internal::Func(12345)); -``` - -## I would like to run a test several times with different parameters. Do I need to write several similar copies of it? ## - -No. You can use a feature called [value-parameterized tests](advanced.md#Value_Parameterized_Tests) which -lets you repeat your tests with different parameters, without defining it more than once. - -## How do I test a file that defines main()? ## - -To test a `foo.cc` file, you need to compile and link it into your unit test -program. However, when the file contains a definition for the `main()` -function, it will clash with the `main()` of your unit test, and will result in -a build error. +## Why should I prefer test fixtures over global variables? -The right solution is to split it into three files: - 1. `foo.h` which contains the declarations, - 1. `foo.cc` which contains the definitions except `main()`, and - 1. `foo_main.cc` which contains nothing but the definition of `main()`. - -Then `foo.cc` can be easily tested. - -If you are adding tests to an existing file and don't want an intrusive change -like this, there is a hack: just include the entire `foo.cc` file in your unit -test. For example: -```c++ -// File foo_unittest.cc - -// The headers section -... - -// Renames main() in foo.cc to make room for the unit test main() -#define main FooMain - -#include "a/b/foo.cc" - -// The tests start here. -... -``` +There are several good reasons: +1. It's likely your test needs to change the states of its global variables. + This makes it difficult to keep side effects from escaping one test and + contaminating others, making debugging difficult. By using fixtures, each + test has a fresh set of variables that's different (but with the same + names). Thus, tests are kept independent of each other. +1. Global variables pollute the global namespace. +1. Test fixtures can be reused via subclassing, which cannot be done easily + with global variables. This is useful if many test cases have something in + common. -However, please remember this is a hack and should only be used as the last -resort. -## What can the statement argument in ASSERT\_DEATH() be? ## + ## What can the statement argument in ASSERT_DEATH() be? -`ASSERT_DEATH(_statement_, _regex_)` (or any death assertion macro) can be used -wherever `_statement_` is valid. So basically `_statement_` can be any C++ +`ASSERT_DEATH(*statement*, *regex*)` (or any death assertion macro) can be used +wherever `*statement*` is valid. So basically `*statement*` can be any C++ statement that makes sense in the current context. In particular, it can reference global and/or local variables, and can be: - * a simple function call (often the case), - * a complex expression, or - * a compound statement. + +* a simple function call (often the case), +* a complex expression, or +* a compound statement. Some examples are shown here: @@ -818,7 +569,7 @@ TEST(MyDeathTest, ComplexExpression) { "(Func1|Method) failed"); } -// Death assertions can be used any where in a function. In +// Death assertions can be used any where in a function. In // particular, they can be inside a loop. TEST(MyDeathTest, InsideLoop) { // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die. @@ -837,49 +588,47 @@ TEST(MyDeathTest, CompoundStatement) { Bar(i); } }, - "Bar has \\d+ errors");} + "Bar has \\d+ errors"); +} ``` -`googletest_unittest.cc` contains more examples if you are interested. - -## What syntax does the regular expression in ASSERT\_DEATH use? ## +gtest-death-test_test.cc contains more examples if you are interested. -On POSIX systems, Google Test uses the POSIX Extended regular -expression syntax -(http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). -On Windows, it uses a limited variant of regular expression -syntax. For more details, see the -[regular expression syntax](advanced.md#Regular_Expression_Syntax). +## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why? -## I have a fixture class Foo, but TEST\_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? ## +Googletest needs to be able to create objects of your test fixture class, so it +must have a default constructor. Normally the compiler will define one for you. +However, there are cases where you have to define your own: -Google Test needs to be able to create objects of your test fixture class, so -it must have a default constructor. Normally the compiler will define one for -you. However, there are cases where you have to define your own: - * If you explicitly declare a non-default constructor for class `Foo`, then you need to define a default constructor, even if it would be empty. - * If `Foo` has a const non-static data member, then you have to define the default constructor _and_ initialize the const member in the initializer list of the constructor. (Early versions of `gcc` doesn't force you to initialize the const member. It's a bug that has been fixed in `gcc 4`.) +* If you explicitly declare a non-default constructor for class `FooTest` + (`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a + default constructor, even if it would be empty. +* If `FooTest` has a const non-static data member, then you have to define the + default constructor *and* initialize the const member in the initializer + list of the constructor. (Early versions of `gcc` doesn't force you to + initialize the const member. It's a bug that has been fixed in `gcc 4`.) -## Why does ASSERT\_DEATH complain about previous threads that were already joined? ## +## Why does ASSERT_DEATH complain about previous threads that were already joined? -With the Linux pthread library, there is no turning back once you cross the -line from single thread to multiple threads. The first time you create a -thread, a manager thread is created in addition, so you get 3, not 2, threads. -Later when the thread you create joins the main thread, the thread count -decrements by 1, but the manager thread will never be killed, so you still have -2 threads, which means you cannot safely run a death test. +With the Linux pthread library, there is no turning back once you cross the line +from single thread to multiple threads. The first time you create a thread, a +manager thread is created in addition, so you get 3, not 2, threads. Later when +the thread you create joins the main thread, the thread count decrements by 1, +but the manager thread will never be killed, so you still have 2 threads, which +means you cannot safely run a death test. The new NPTL thread library doesn't suffer from this problem, as it doesn't create a manager thread. However, if you don't control which machine your test runs on, you shouldn't depend on this. -## Why does Google Test require the entire test case, instead of individual tests, to be named FOODeathTest when it uses ASSERT\_DEATH? ## +## Why does googletest require the entire test case, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH? -Google Test does not interleave tests from different test cases. That is, it -runs all tests in one test case first, and then runs all tests in the next test -case, and so on. Google Test does this because it needs to set up a test case -before the first test in it is run, and tear it down afterwords. Splitting up -the test case would require multiple set-up and tear-down processes, which is -inefficient and makes the semantics unclean. +googletest does not interleave tests from different test cases. That is, it runs +all tests in one test case first, and then runs all tests in the next test case, +and so on. googletest does this because it needs to set up a test case before +the first test in it is run, and tear it down afterwords. Splitting up the test +case would require multiple set-up and tear-down processes, which is inefficient +and makes the semantics unclean. If we were to determine the order of tests based on test name instead of test case name, then we would have a problem with the following situation: @@ -897,7 +646,7 @@ interleave tests from different test cases, we need to run all tests in the `FooTest` case before running any test in the `BarTest` case. This contradicts with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`. -## But I don't like calling my entire test case FOODeathTest when it contains both death tests and non-death tests. What do I do? ## +## But I don't like calling my entire test case \*DeathTest when it contains both death tests and non-death tests. What do I do? You don't have to, but if you like, you may split up the test case into `FooTest` and `FooDeathTest`, where the names make it clear that they are @@ -909,119 +658,81 @@ class FooTest : public ::testing::Test { ... }; TEST_F(FooTest, Abc) { ... } TEST_F(FooTest, Def) { ... } -typedef FooTest FooDeathTest; +using FooDeathTest = FooTest; TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... } TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... } ``` -## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? ## +## googletest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds? + +Printing the LOG messages generated by the statement inside `EXPECT_DEATH()` +makes it harder to search for real problems in the parent's log. Therefore, +googletest only prints them when the death test has failed. + +If you really need to see such LOG messages, a workaround is to temporarily +break the death test (e.g. by changing the regex pattern it is expected to +match). Admittedly, this is a hack. We'll consider a more permanent solution +after the fork-and-exec-style death tests are implemented. + +## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? If you use a user-defined type `FooType` in an assertion, you must make sure there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function defined such that we can print a value of `FooType`. In addition, if `FooType` is declared in a name space, the `<<` operator also -needs to be defined in the _same_ name space. +needs to be defined in the *same* name space. See go/totw/49 for details. -## How do I suppress the memory leak messages on Windows? ## +## How do I suppress the memory leak messages on Windows? -Since the statically initialized Google Test singleton requires allocations on +Since the statically initialized googletest singleton requires allocations on the heap, the Visual C++ memory leak detector will report memory leaks at the end of the program run. The easiest way to avoid this is to use the `_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any statically initialized heap objects. See MSDN for more details and additional heap check/debug routines. -## I am building my project with Google Test in Visual Studio and all I'm getting is a bunch of linker errors (or warnings). Help! ## - -You may get a number of the following linker error or warnings if you -attempt to link your test project with the Google Test library when -your project and the are not built using the same compiler settings. - - * LNK2005: symbol already defined in object - * LNK4217: locally defined symbol 'symbol' imported in function 'function' - * LNK4049: locally defined symbol 'symbol' imported - -The Google Test project (gtest.vcproj) has the Runtime Library option -set to /MT (use multi-threaded static libraries, /MTd for debug). If -your project uses something else, for example /MD (use multi-threaded -DLLs, /MDd for debug), you need to change the setting in the Google -Test project to match your project's. - -To update this setting open the project properties in the Visual -Studio IDE then select the branch Configuration Properties | C/C++ | -Code Generation and change the option "Runtime Library". You may also try -using gtest-md.vcproj instead of gtest.vcproj. - -## I put my tests in a library and Google Test doesn't run them. What's happening? ## -Have you read a -[warning](primer.md#important-note-for-visual-c-users) on -the Google Test Primer page? - -## I want to use Google Test with Visual Studio but don't know where to start. ## -Many people are in your position and one of them posted his solution to our mailing list. - -## I am seeing compile errors mentioning std::type\_traits when I try to use Google Test on Solaris. ## -Google Test uses parts of the standard C++ library that SunStudio does not support. -Our users reported success using alternative implementations. Try running the build after running this command: - -`export CC=cc CXX=CC CXXFLAGS='-library=stlport4'` - -## How can my code detect if it is running in a test? ## - -If you write code that sniffs whether it's running in a test and does -different things accordingly, you are leaking test-only logic into -production code and there is no easy way to ensure that the test-only -code paths aren't run by mistake in production. Such cleverness also -leads to -[Heisenbugs](http://en.wikipedia.org/wiki/Unusual_software_bug#Heisenbug). -Therefore we strongly advise against the practice, and Google Test doesn't -provide a way to do it. - -In general, the recommended way to cause the code to behave -differently under test is [dependency injection](http://jamesshore.com/Blog/Dependency-Injection-Demystified.html). -You can inject different functionality from the test and from the -production code. Since your production code doesn't link in the -for-test logic at all, there is no danger in accidentally running it. - -However, if you _really_, _really_, _really_ have no choice, and if -you follow the rule of ending your test program names with `_test`, -you can use the _horrible_ hack of sniffing your executable name -(`argv[0]` in `main()`) to know whether the code is under test. - -## Google Test defines a macro that clashes with one defined by another library. How do I deal with that? ## - -In C++, macros don't obey namespaces. Therefore two libraries that -both define a macro of the same name will clash if you `#include` both -definitions. In case a Google Test macro clashes with another -library, you can force Google Test to rename its macro to avoid the -conflict. - -Specifically, if both Google Test and some other code define macro -`FOO`, you can add -``` - -DGTEST_DONT_DEFINE_FOO=1 -``` -to the compiler flags to tell Google Test to change the macro's name -from `FOO` to `GTEST_FOO`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write -```c++ - GTEST_TEST(SomeTest, DoesThis) { ... } -``` -instead of -```c++ - TEST(SomeTest, DoesThis) { ... } -``` -in order to define a test. -Currently, the following `TEST`, `FAIL`, `SUCCEED`, and the basic comparison assertion macros can have . You can see the full list of covered macros [here](../include/gtest/gtest.h). More information can be found in the "Avoiding Macro Name Clashes" section of the README file. +## How can my code detect if it is running in a test? + +If you write code that sniffs whether it's running in a test and does different +things accordingly, you are leaking test-only logic into production code and +there is no easy way to ensure that the test-only code paths aren't run by +mistake in production. Such cleverness also leads to +[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly +advise against the practice, and googletest doesn't provide a way to do it. + +In general, the recommended way to cause the code to behave differently under +test is [Dependency Injection](http://go/dependency-injection). You can inject +different functionality from the test and from the production code. Since your +production code doesn't link in the for-test logic at all (the +[`testonly`](http://go/testonly) attribute for BUILD targets helps to ensure +that), there is no danger in accidentally running it. +However, if you *really*, *really*, *really* have no choice, and if you follow +the rule of ending your test program names with `_test`, you can use the +*horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know +whether the code is under test. -## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? ## + +## How do I temporarily disable a test? + +If you have a broken test that you cannot fix right away, you can add the +DISABLED_ prefix to its name. This will exclude it from execution. This is +better than commenting out the code or using #if 0, as disabled tests are still +compiled (and thus won't rot). + +To include disabled tests in test execution, just invoke the test program with +the --gtest_also_run_disabled_tests flag. + +## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? Yes. -The rule is **all test methods in the same test case must use the same fixture class**. This means that the following is **allowed** because both tests use the same fixture class (`::testing::Test`). +The rule is **all test methods in the same test case must use the same fixture +class.** This means that the following is **allowed** because both tests use the +same fixture class (`::testing::Test`). ```c++ namespace foo { @@ -1037,7 +748,9 @@ TEST(CoolTest, DoSomething) { } // namespace bar ``` -However, the following code is **not allowed** and will produce a runtime error from Google Test because the test methods are using different test fixture classes with the same test case name. +However, the following code is **not allowed** and will produce a runtime error +from googletest because the test methods are using different test fixture +classes with the same test case name. ```c++ namespace foo { @@ -1054,39 +767,3 @@ TEST_F(CoolTest, DoSomething) { } } // namespace bar ``` - -## How do I build Google Testing Framework with Xcode 4? ## - -If you try to build Google Test's Xcode project with Xcode 4.0 or later, you may encounter an error message that looks like -"Missing SDK in target gtest\_framework: /Developer/SDKs/MacOSX10.4u.sdk". That means that Xcode does not support the SDK the project is targeting. See the Xcode section in the [README](../README.md) file on how to resolve this. - -## How do I easily discover the flags needed for GoogleTest? ## - -GoogleTest (and GoogleMock) now support discovering all necessary flags using pkg-config. -See the [pkg-config guide](Pkgconfig.md) on how you can easily discover all compiler and -linker flags using pkg-config. - -## My question is not covered in your FAQ! ## - -If you cannot find the answer to your question in this FAQ, there are -some other resources you can use: - - 1. read other [wiki pages](../docs), - 1. search the mailing list [archive](https://groups.google.com/forum/#!forum/googletestframework), - 1. ask it on [googletestframework@googlegroups.com](mailto:googletestframework@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googletestframework) before you can post.). - -Please note that creating an issue in the -[issue tracker](https://github.com/google/googletest/issues) is _not_ -a good way to get your answer, as it is monitored infrequently by a -very small number of people. - -When asking a question, it's helpful to provide as much of the -following information as possible (people cannot help you if there's -not enough information in your question): - - * the version (or the commit hash if you check out from Git directly) of Google Test you use (Google Test is under active development, so it's possible that your problem has been solved in a later version), - * your operating system, - * the name and version of your compiler, - * the complete command line flags you give to your compiler, - * the complete compiler error messages (if the question is about compilation), - * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter. diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 9949658..b80418e 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -1,5 +1,6 @@ # Googletest Primer + ## Introduction: Why googletest? *googletest* helps you write better C++ tests. @@ -436,6 +437,7 @@ When these tests run, the following happens: **Availability**: Linux, Windows, Mac. + ## Invoking the Tests `TEST()` and `TEST_F()` implicitly register their tests with googletest. So, @@ -544,6 +546,7 @@ int main(int argc, char **argv) { } ``` + The `::testing::InitGoogleTest()` function parses the command line for googletest flags, and removes all recognized flags. This allows the user to control a test program's behavior via various flags, which we'll cover in @@ -560,6 +563,7 @@ gtest\_main library and you are good to go. NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`. + ## Known Limitations * Google Test is designed to be thread-safe. The implementation is thread-safe -- cgit v0.12 From 7e73a7ae6e665e3a9e34543090625ab8278412bb Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 18 Jul 2018 11:17:19 -0400 Subject: Formatting and a link --- googlemock/include/gmock/internal/custom/gmock-matchers.h | 2 +- googletest/include/gtest/internal/gtest-port.h | 2 +- googletest/src/gtest.cc | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/googlemock/include/gmock/internal/custom/gmock-matchers.h b/googlemock/include/gmock/internal/custom/gmock-matchers.h index fe0d9e8..af8240e 100644 --- a/googlemock/include/gmock/internal/custom/gmock-matchers.h +++ b/googlemock/include/gmock/internal/custom/gmock-matchers.h @@ -32,7 +32,7 @@ // ============================================================ // // Adds google3 callback support to CallableTraits. -// + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index d5ec086..bc35c34 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -1218,7 +1218,7 @@ class scoped_ptr { // Defines RE. #if GTEST_USES_PCRE -using ::RE; +// if used, PCRE is injected by custom/gtest-port.h #elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE // A simple C++ wrapper for . It uses the POSIX Extended diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 9c25c99..26a3710 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -5273,7 +5273,7 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { // each TestCase and TestInfo object. // If shard_tests == true, further filters tests based on sharding // variables in the environment - see -// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md +// https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md // . Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? -- cgit v0.12 From 8d07cfd0532352379c624ce8844aeca0dc68a585 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 18 Jul 2018 11:30:36 -0400 Subject: Code sync, mostly formatting and removing outdates --- googlemock/test/gmock-actions_test.cc | 202 ---------------------------------- googlemock/test/gmock_ex_test.cc | 3 +- 2 files changed, 2 insertions(+), 203 deletions(-) diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index 7fbb50d..e8bdbee 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -88,10 +88,6 @@ using testing::tuple_element; using testing::SetErrnoAndReturn; #endif -#if GTEST_HAS_PROTOBUF_ -using testing::internal::TestMessage; -#endif // GTEST_HAS_PROTOBUF_ - // Tests that BuiltInDefaultValue::Get() returns NULL. TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) { EXPECT_TRUE(BuiltInDefaultValue::Get() == NULL); @@ -895,105 +891,6 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) { # endif } -#if GTEST_HAS_PROTOBUF_ - -// Tests that SetArgPointee(proto_buffer) sets the v1 protobuf -// variable pointed to by the N-th (0-based) argument to proto_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgPointee<1>(*msg); - // SetArgPointee(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, &dest)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgPointee(proto_buffer) sets the -// ::ProtocolMessage variable pointed to by the N-th (0-based) -// argument to proto_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgPointee<1>(*msg); - // SetArgPointee(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - ::ProtocolMessage* const dest_base = &dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, dest_base)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgPointee(proto2_buffer) sets the v2 -// protobuf variable pointed to by the N-th (0-based) argument to -// proto2_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgPointee<1>(*msg); - // SetArgPointee(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - a.Perform(make_tuple(true, &dest)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -// Tests that SetArgPointee(proto2_buffer) sets the -// proto2::Message variable pointed to by the N-th (0-based) argument -// to proto2_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgPointee<1>(*msg); - // SetArgPointee(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - ::proto2::Message* const dest_base = &dest; - a.Perform(make_tuple(true, dest_base)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -#endif // GTEST_HAS_PROTOBUF_ - // Tests that SetArgumentPointee(v) sets the variable pointed to by // the N-th (0-based) argument to v. TEST(SetArgumentPointeeTest, SetsTheNthPointee) { @@ -1014,105 +911,6 @@ TEST(SetArgumentPointeeTest, SetsTheNthPointee) { EXPECT_EQ('a', ch); } -#if GTEST_HAS_PROTOBUF_ - -// Tests that SetArgumentPointee(proto_buffer) sets the v1 protobuf -// variable pointed to by the N-th (0-based) argument to proto_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, &dest)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgumentPointee(proto_buffer) sets the -// ::ProtocolMessage variable pointed to by the N-th (0-based) -// argument to proto_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - ::ProtocolMessage* const dest_base = &dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, dest_base)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgumentPointee(proto2_buffer) sets the v2 -// protobuf variable pointed to by the N-th (0-based) argument to -// proto2_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - a.Perform(make_tuple(true, &dest)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -// Tests that SetArgumentPointee(proto2_buffer) sets the -// proto2::Message variable pointed to by the N-th (0-based) argument -// to proto2_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - ::proto2::Message* const dest_base = &dest; - a.Perform(make_tuple(true, dest_base)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -#endif // GTEST_HAS_PROTOBUF_ - // Sample functions and functors for testing Invoke() and etc. int Nullary() { return 1; } diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc index 99268b3..b03de82 100644 --- a/googlemock/test/gmock_ex_test.cc +++ b/googlemock/test/gmock_ex_test.cc @@ -38,6 +38,7 @@ namespace { using testing::HasSubstr; + using testing::internal::GoogleTestFailureException; // A type that cannot be default constructed. @@ -53,7 +54,6 @@ class MockFoo { MOCK_METHOD0(GetNonDefaultConstructible, NonDefaultConstructible()); }; - TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { MockFoo mock; try { @@ -76,5 +76,6 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { } } + } // unnamed namespace #endif -- cgit v0.12 From d41bfd732f3980c573f8fa27faf4d38d7fb16a45 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 18 Jul 2018 11:38:18 -0400 Subject: Fix link --- googletest/src/gtest.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 26a3710..9c25c99 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -5273,7 +5273,7 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { // each TestCase and TestInfo object. // If shard_tests == true, further filters tests based on sharding // variables in the environment - see -// https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md +// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md // . Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? -- cgit v0.12 From 3530ab9e437b57e9d6778f646d5b88343cae5e02 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 18 Jul 2018 11:51:14 -0400 Subject: Code sync --- googlemock/test/gmock-matchers_test.cc | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index 87b2ad5..a451842 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -2680,7 +2680,7 @@ TEST(AllOfTest, ExplainsResult) { } // Helper to allow easy testing of AnyOf matchers with num parameters. -void AnyOfMatches(int num, const Matcher& m) { +static void AnyOfMatches(int num, const Matcher& m) { SCOPED_TRACE(Describe(m)); EXPECT_FALSE(m.Matches(0)); for (int i = 1; i <= num; ++i) { @@ -2689,6 +2689,18 @@ void AnyOfMatches(int num, const Matcher& m) { EXPECT_FALSE(m.Matches(num + 1)); } +#if GTEST_LANG_CXX11 +static void AnyOfStringMatches(int num, const Matcher& m) { + SCOPED_TRACE(Describe(m)); + EXPECT_FALSE(m.Matches(std::to_string(0))); + + for (int i = 1; i <= num; ++i) { + EXPECT_TRUE(m.Matches(std::to_string(i))); + } + EXPECT_FALSE(m.Matches(std::to_string(num + 1))); +} +#endif + // Tests that AnyOf(m1, ..., mn) matches any value that matches at // least one of the given matchers. TEST(AnyOfTest, MatchesWhenAnyMatches) { @@ -2746,6 +2758,12 @@ TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)); + AnyOfStringMatches( + 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", + "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", + "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", + "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", + "43", "44", "45", "46", "47", "48", "49", "50")); } // Tests the variadic version of the ElementsAreMatcher @@ -4570,7 +4588,7 @@ TEST(ResultOfTest, WorksForFunctors) { } // Tests that ResultOf(f, ...) compiles and works as expected when f is a -// functor with more then one operator() defined. ResultOf() must work +// functor with more than one operator() defined. ResultOf() must work // for each defined operator(). struct PolymorphicFunctor { typedef int result_type; @@ -6764,4 +6782,3 @@ TEST(NotTest, WorksOnMoveOnlyType) { } // namespace gmock_matchers_test } // namespace testing - -- cgit v0.12 From 0c17888bcfa7a05ae2cb14c1f5e2451ea9745211 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 19 Jul 2018 12:42:39 -0400 Subject: code sync --- googlemock/include/gmock/gmock-matchers.h | 12 ++++++++---- googlemock/test/gmock-matchers_test.cc | 1 + 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index c94f582..7fd5787 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -5165,13 +5165,17 @@ std::string DescribeMatcher(const M& matcher, bool negation = false) { // Define variadic matcher versions. They are overloaded in // gmock-generated-matchers.h for the cases supported by pre C++11 compilers. template -internal::AllOfMatcher AllOf(const Args&... matchers) { - return internal::AllOfMatcher(matchers...); +internal::AllOfMatcher::type...> AllOf( + const Args&... matchers) { + return internal::AllOfMatcher::type...>( + matchers...); } template -internal::AnyOfMatcher AnyOf(const Args&... matchers) { - return internal::AnyOfMatcher(matchers...); +internal::AnyOfMatcher::type...> AnyOf( + const Args&... matchers) { + return internal::AnyOfMatcher::type...>( + matchers...); } template diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index a451842..f9dfd3c 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -2795,6 +2795,7 @@ TEST(ElementsAreTest, HugeMatcherUnordered) { #endif // GTEST_LANG_CXX11 + // Tests that AnyOf(m1, ..., mn) describes itself properly. TEST(AnyOfTest, CanDescribeSelf) { Matcher m; -- cgit v0.12 From 2eb43960076417a3dca33ea5ad58e3e9feaee6e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=9C=E4=BF=AE=E6=9D=8F?= Date: Fri, 20 Jul 2018 06:15:13 +0800 Subject: =?UTF-8?q?Replace=20"=E2=80=A6"=20with=20"..."(three=20dots)=20to?= =?UTF-8?q?=20fix=20warning=20C4819=20in=20Visual=20Studio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- googlemock/docs/CookBook.md | 4 ++-- googlemock/include/gmock/gmock-generated-function-mockers.h.pump | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/googlemock/docs/CookBook.md b/googlemock/docs/CookBook.md index bd9f026..8809b0e 100644 --- a/googlemock/docs/CookBook.md +++ b/googlemock/docs/CookBook.md @@ -2247,7 +2247,7 @@ enum class AccessLevel { kInternal, kPublic }; class Buzz { public: - explicit Buzz(AccessLevel access) { … } + explicit Buzz(AccessLevel access) { ... } ... }; @@ -2320,7 +2320,7 @@ Note that `ByMove()` is essential here - if you drop it, the code won’t compil Quiz time! What do you think will happen if a `Return(ByMove(...))` action is performed more than once (e.g. you write -`….WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first +`.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time the action runs, the source value will be consumed (since it’s a move-only value), so the next time around, there’s no value to move from -- you’ll get a run-time error that `Return(ByMove(...))` can only be run once. diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump index efcb3e8..9865922 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump @@ -114,7 +114,7 @@ class FunctionMocker : public // // class MockClass { // // Overload 1 -// MockSpec gmock_GetName() { … } +// MockSpec gmock_GetName() { ... } // // Overload 2. Declared const so that the compiler will generate an // // error when trying to resolve between this and overload 4 in // // 'gmock_GetName(WithoutMatchers(), nullptr)'. @@ -125,7 +125,7 @@ class FunctionMocker : public // } // // // Overload 3 -// const string& gmock_GetName() const { … } +// const string& gmock_GetName() const { ... } // // Overload 4 // MockSpec gmock_GetName( // const WithoutMatchers&, const Function*) const { -- cgit v0.12 From a02af2f689426aa9622b06643f53ed27fa6dc8a5 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 20 Jul 2018 11:28:58 -0400 Subject: code merge --- googlemock/include/gmock/gmock-matchers.h | 14 ++++++++++++++ googlemock/test/gmock-matchers_test.cc | 5 ++++- googletest/include/gtest/internal/gtest-port.h | 4 ---- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 7fd5787..eb09613 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -4529,6 +4529,20 @@ Property(PropertyType (Class::*property)() const &, property, MatcherCast(matcher))); } + +// Three-argument form for reference-qualified member functions. +template +inline PolymorphicMatcher > +Property(const std::string& property_name, + PropertyType (Class::*property)() const &, + const PropertyMatcher& matcher) { + return MakePolymorphicMatcher( + internal::PropertyMatcher( + property_name, property, + MatcherCast(matcher))); +} #endif // Creates a matcher that matches an object iff the result of applying diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index f9dfd3c..9f1a547 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -2795,7 +2795,6 @@ TEST(ElementsAreTest, HugeMatcherUnordered) { #endif // GTEST_LANG_CXX11 - // Tests that AnyOf(m1, ..., mn) describes itself properly. TEST(AnyOfTest, CanDescribeSelf) { Matcher m; @@ -4239,13 +4238,17 @@ TEST(PropertyTest, WorksForReferenceToConstProperty) { // ref-qualified. TEST(PropertyTest, WorksForRefQualifiedProperty) { Matcher m = Property(&AClass::s_ref, StartsWith("hi")); + Matcher m_with_name = + Property("s", &AClass::s_ref, StartsWith("hi")); AClass a; a.set_s("hill"); EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.set_s("hole"); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } #endif diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index bc35c34..dbe703b 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -522,11 +522,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #endif // !defined(GTEST_HAS_STD_STRING) #ifndef GTEST_HAS_GLOBAL_STRING -// The user didn't tell us whether ::string is available, so we need -// to figure it out. - # define GTEST_HAS_GLOBAL_STRING 0 - #endif // GTEST_HAS_GLOBAL_STRING #ifndef GTEST_HAS_STD_WSTRING -- cgit v0.12 From baf2115a592758f207c52dd95db42b1962c7aac7 Mon Sep 17 00:00:00 2001 From: Stian Valle Date: Sat, 21 Jul 2018 15:29:58 +0200 Subject: Update primer.md --- googletest/docs/primer.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index f7f26eb..81d8be4 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -203,7 +203,7 @@ for more details. If you're working with floating point numbers, you may want to use the floating point variations of some of these macros in order to avoid problems caused by -rounding. See [Advanced googletest Topics](advanced) for details. +rounding. See [Advanced googletest Topics](advanced.md) for details. Macros in this section work with both narrow and wide string objects (`string` and `wstring`). @@ -222,15 +222,15 @@ two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead. | Fatal assertion | Nonfatal assertion | Verifies | | ----------------------- | ----------------------- | ---------------------- | | `ASSERT_STREQ(str1, | `EXPECT_STREQ(str1, | the two C strings have | -: str2);` : str2);` : the same content : +| str2);` | str2);` | the same content | | `ASSERT_STRNE(str1, | `EXPECT_STRNE(str1, | the two C strings have | -: str2);` : str2);` : different contents : +| str2);` | str2);` | different contents | | `ASSERT_STRCASEEQ(str1, | `EXPECT_STRCASEEQ(str1, | the two C strings have | -: str2);` : str2);` : the same content, : -: : : ignoring case : +| str2);` | str2);` | the same content, | +| | | ignoring case | | `ASSERT_STRCASENE(str1, | `EXPECT_STRCASENE(str1, | the two C strings have | -: str2);` : str2);` : different contents, : -: : : ignoring case : +| str2);` | str2);` | different contents, | +| | | ignoring case | Note that "CASE" in an assertion name means that case is ignored. A `NULL` pointer and an empty string are considered *different*. -- cgit v0.12 From 7abf99d941ba0c865114702bff4b4e88b3e34564 Mon Sep 17 00:00:00 2001 From: Stian Valle Date: Sat, 21 Jul 2018 15:40:57 +0200 Subject: Update primer.md --- googletest/docs/primer.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 81d8be4..7e03112 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -219,18 +219,18 @@ as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now The assertions in this group compare two **C strings**. If you want to compare two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead. -| Fatal assertion | Nonfatal assertion | Verifies | -| ----------------------- | ----------------------- | ---------------------- | -| `ASSERT_STREQ(str1, | `EXPECT_STREQ(str1, | the two C strings have | -| str2);` | str2);` | the same content | -| `ASSERT_STRNE(str1, | `EXPECT_STRNE(str1, | the two C strings have | -| str2);` | str2);` | different contents | -| `ASSERT_STRCASEEQ(str1, | `EXPECT_STRCASEEQ(str1, | the two C strings have | -| str2);` | str2);` | the same content, | -| | | ignoring case | -| `ASSERT_STRCASENE(str1, | `EXPECT_STRCASENE(str1, | the two C strings have | -| str2);` | str2);` | different contents, | -| | | ignoring case | +| Fatal assertion | Nonfatal assertion | Verifies | +| ------------------------ | ------------------------ | ---------------------- | +| `ASSERT_STREQ(str1,` | `EXPECT_STREQ(str1,` | the two C strings have | +| `str2);` | `str2);` | the same content | +| `ASSERT_STRNE(str1,` | `EXPECT_STRNE(str1,` | the two C strings have | +| `str2);` | `str2);` | different contents | +| `ASSERT_STRCASEEQ(str1,` | `EXPECT_STRCASEEQ(str1,` | the two C strings have | +| `str2);` | `str2);` | the same content, | +| | | ignoring case | +| `ASSERT_STRCASENE(str1,` | `EXPECT_STRCASENE(str1,` | the two C strings have | +| `str2);` | `str2);` | different contents, | +| | | ignoring case | Note that "CASE" in an assertion name means that case is ignored. A `NULL` pointer and an empty string are considered *different*. -- cgit v0.12 From bb9fc6f66e4954576a51cc05c99f01ff97c2da29 Mon Sep 17 00:00:00 2001 From: Stian Valle Date: Sat, 21 Jul 2018 15:50:45 +0200 Subject: Update primer.md --- googletest/docs/primer.md | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 7e03112..260d50b 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -219,18 +219,12 @@ as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now The assertions in this group compare two **C strings**. If you want to compare two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead. -| Fatal assertion | Nonfatal assertion | Verifies | -| ------------------------ | ------------------------ | ---------------------- | -| `ASSERT_STREQ(str1,` | `EXPECT_STREQ(str1,` | the two C strings have | -| `str2);` | `str2);` | the same content | -| `ASSERT_STRNE(str1,` | `EXPECT_STRNE(str1,` | the two C strings have | -| `str2);` | `str2);` | different contents | -| `ASSERT_STRCASEEQ(str1,` | `EXPECT_STRCASEEQ(str1,` | the two C strings have | -| `str2);` | `str2);` | the same content, | -| | | ignoring case | -| `ASSERT_STRCASENE(str1,` | `EXPECT_STRCASENE(str1,` | the two C strings have | -| `str2);` | `str2);` | different contents, | -| | | ignoring case | +| Fatal assertion | Nonfatal assertion | Verifies | +| ------------------------------- | ------------------------------- | -------------------------------------------------------- | +| `ASSERT_STREQ(str1, str2);` | `EXPECT_STREQ(str1, str2);` | the two C strings have the same content | +| `ASSERT_STRNE(str1, str2);` | `EXPECT_STRNE(str1, str2);` | the two C strings have different contents | +| `ASSERT_STRCASEEQ(str1, str2);` | `EXPECT_STRCASEEQ(str1, str2);` | the two C strings have the same content, ignoring case | +| `ASSERT_STRCASENE(str1, str2);` | `EXPECT_STRCASENE(str1, str2);` | the two C strings have different contents, ignoring case | Note that "CASE" in an assertion name means that case is ignored. A `NULL` pointer and an empty string are considered *different*. -- cgit v0.12 From ed1edf641dc5a04dc559df763ca71a5d6d05d939 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 25 Jul 2018 10:24:13 -0400 Subject: Formatting changes, code sync --- googlemock/test/gmock_stress_test.cc | 3 +-- googletest/include/gtest/internal/gtest-string.h | 3 +-- googletest/test/gtest_prod_test.cc | 2 +- googletest/test/gtest_unittest.cc | 4 ++-- 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/googlemock/test/gmock_stress_test.cc b/googlemock/test/gmock_stress_test.cc index b9fdc45..e4e61f0 100644 --- a/googlemock/test/gmock_stress_test.cc +++ b/googlemock/test/gmock_stress_test.cc @@ -33,13 +33,12 @@ // threads concurrently. #include "gmock/gmock.h" - #include "gtest/gtest.h" namespace testing { namespace { -// From "gtest/internal/gtest-port.h". +// From gtest-port.h. using ::testing::internal::ThreadWithParam; // The maximum number of test threads (not including helper threads) diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h index 71eb840..64da26c 100644 --- a/googletest/include/gtest/internal/gtest-string.h +++ b/googletest/include/gtest/internal/gtest-string.h @@ -34,8 +34,7 @@ // Google Test. They are subject to change without notice. They should not used // by code external to Google Test. // -// This header file is #included by -// gtest/internal/gtest-internal.h. +// This header file is #included by gtest-internal.h. // It should not be #included by other files. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ diff --git a/googletest/test/gtest_prod_test.cc b/googletest/test/gtest_prod_test.cc index dfb9998..c5cceab 100644 --- a/googletest/test/gtest_prod_test.cc +++ b/googletest/test/gtest_prod_test.cc @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) // -// Unit test for gtest/gtest_prod.h. +// Unit test for gtest_prod.h. #include "production.h" #include "gtest/gtest.h" diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 39b6841..8ebb667 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -35,8 +35,8 @@ #include "gtest/gtest.h" // Verifies that the command line flag variables can be accessed in -// code once "gtest/gtest.h" has been -// #included. Do not move it after other gtest #includes. +// code once "gtest.h" has been #included. +// Do not move it after other gtest #includes. TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { bool dummy = testing::GTEST_FLAG(also_run_disabled_tests) || testing::GTEST_FLAG(break_on_failure) -- cgit v0.12 From 309e8a271e9aca1ef4aab899ce5d2d07c42123bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20K=C4=85kol?= Date: Wed, 25 Jul 2018 19:19:26 +0200 Subject: Updated broken and outdated URLs --- .travis.yml | 2 +- googlemock/docs/ForDummies.md | 2 +- googlemock/docs/FrequentlyAskedQuestions.md | 2 +- googlemock/scripts/upload.py | 8 ++++---- googlemock/src/gmock_main.cc | 2 +- googletest/cmake/internal_utils.cmake | 2 +- googletest/docs/XcodeGuide.md | 8 ++++---- googletest/docs/advanced.md | 16 ++++++++-------- googletest/docs/faq.md | 6 +++--- googletest/docs/primer.md | 6 +++--- googletest/include/gtest/internal/gtest-port.h | 6 +++--- googletest/scripts/upload.py | 8 ++++---- googletest/src/gtest-port.cc | 2 +- googletest/test/gtest-death-test_test.cc | 2 +- googletest/xcode/Config/DebugProject.xcconfig | 2 +- googletest/xcode/Config/FrameworkTarget.xcconfig | 2 +- googletest/xcode/Config/General.xcconfig | 2 +- googletest/xcode/Config/ReleaseProject.xcconfig | 2 +- googletest/xcode/Config/StaticLibraryTarget.xcconfig | 2 +- 19 files changed, 41 insertions(+), 41 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1200c67..0e17bc2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ # Build matrix / environment variable are explained on: -# http://about.travis-ci.org/docs/user/build-configuration/ +# https://docs.travis-ci.com/user/customizing-the-build/ # This file can be validated on: # http://lint.travis-ci.org/ diff --git a/googlemock/docs/ForDummies.md b/googlemock/docs/ForDummies.md index 1e0fd41..566a34e 100644 --- a/googlemock/docs/ForDummies.md +++ b/googlemock/docs/ForDummies.md @@ -170,7 +170,7 @@ Admittedly, this test is contrived and doesn't do much. You can easily achieve t ## Using Google Mock with Any Testing Framework ## If you want to use something other than Google Test (e.g. [CppUnit](http://sourceforge.net/projects/cppunit/) or -[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to: +[CxxTest](https://cxxtest.com/)) as your testing framework, just change the `main()` function in the previous section to: ``` int main(int argc, char** argv) { // The following line causes Google Mock to throw an exception on failure, diff --git a/googlemock/docs/FrequentlyAskedQuestions.md b/googlemock/docs/FrequentlyAskedQuestions.md index 23f7da0..9008c63 100644 --- a/googlemock/docs/FrequentlyAskedQuestions.md +++ b/googlemock/docs/FrequentlyAskedQuestions.md @@ -528,7 +528,7 @@ interface, which then can be easily mocked. It's a bit of work initially, but usually pays for itself quickly. This Google Testing Blog -[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html) +[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it excellently. Check it out. ## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ## diff --git a/googlemock/scripts/upload.py b/googlemock/scripts/upload.py index 6e6f9a1..95239dc 100755 --- a/googlemock/scripts/upload.py +++ b/googlemock/scripts/upload.py @@ -242,7 +242,7 @@ class AbstractRpcServer(object): The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user - (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). + (see https://developers.google.com/identity/protocols/AuthForInstalledApps). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. @@ -506,7 +506,7 @@ def EncodeMultipartFormData(fields, files): (content_type, body) ready for httplib.HTTP instance. Source: - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 + https://web.archive.org/web/20160116052001/code.activestate.com/recipes/146306 """ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' @@ -807,7 +807,7 @@ class SubversionVCS(VersionControlSystem): # svn cat translates keywords but svn diff doesn't. As a result of this # behavior patching.PatchChunks() fails with a chunk mismatch error. # This part was originally written by the Review Board development team - # who had the same problem (http://reviews.review-board.org/r/276/). + # who had the same problem (https://reviews.reviewboard.org/r/276/). # Mapping of keywords to known aliases svn_keywords = { # Standard keywords @@ -860,7 +860,7 @@ class SubversionVCS(VersionControlSystem): status_lines = status.splitlines() # If file is in a cl, the output will begin with # "\n--- Changelist 'cl_name':\n". See - # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt + # https://web.archive.org/web/20090918234815/svn.collab.net/repos/svn/trunk/notes/changelist-design.txt if (len(status_lines) == 3 and not status_lines[0] and status_lines[1].startswith("--- Changelist")): diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index bd5be03..6182159 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.cc @@ -37,7 +37,7 @@ // causes a link error when _tmain is defined in a static library and UNICODE // is enabled. For this reason instead of _tmain, main function is used on // Windows. See the following link to track the current status of this bug: -// http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=394464 // NOLINT +// https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library // NOLINT #if GTEST_OS_WINDOWS_MOBILE # include // NOLINT diff --git a/googletest/cmake/internal_utils.cmake b/googletest/cmake/internal_utils.cmake index be7af38..086f51c 100644 --- a/googletest/cmake/internal_utils.cmake +++ b/googletest/cmake/internal_utils.cmake @@ -20,7 +20,7 @@ macro(fix_default_compiler_settings_) if (MSVC) # For MSVC, CMake sets certain flags to defaults we want to override. # This replacement code is taken from sample in the CMake Wiki at - # http://www.cmake.org/Wiki/CMake_FAQ#Dynamic_Replace. + # https://gitlab.kitware.com/cmake/community/wikis/FAQ#dynamic-replace. foreach (flag_var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) diff --git a/googletest/docs/XcodeGuide.md b/googletest/docs/XcodeGuide.md index 117265c..1c60a33 100644 --- a/googletest/docs/XcodeGuide.md +++ b/googletest/docs/XcodeGuide.md @@ -6,7 +6,7 @@ This guide will explain how to use the Google Testing Framework in your Xcode pr Here is the quick guide for using Google Test in your Xcode project. - 1. Download the source from the [website](http://code.google.com/p/googletest) using this command: `svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only`. + 1. Download the source from the [website](https://github.com/google/googletest) using this command: `svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only`. 1. Open up the `gtest.xcodeproj` in the `googletest-read-only/xcode/` directory and build the gtest.framework. 1. Create a new "Shell Tool" target in your Xcode project called something like "UnitTests". 1. Add the gtest.framework to your project and add it to the "Link Binary with Libraries" build phase of "UnitTests". @@ -18,7 +18,7 @@ The following sections further explain each of the steps listed above in depth, # Get the Source # -Currently, the gtest.framework discussed here isn't available in a tagged release of Google Test, it is only available in the trunk. As explained at the Google Test [site](http://code.google.com/p/googletest/source/checkout">svn), you can get the code from anonymous SVN with this command: +Currently, the gtest.framework discussed here isn't available in a tagged release of Google Test, it is only available in the trunk. As explained at the Google Test [site](https://github.com/google/googletest), you can get the code from anonymous SVN with this command: ``` svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only @@ -28,7 +28,7 @@ Alternatively, if you are working with Subversion in your own code base, you can To use `svn:externals`, decide where you would like to have the external source reside. You might choose to put the external source inside the trunk, because you want it to be part of the branch when you make a release. However, keeping it outside the trunk in a version-tagged directory called something like `third-party/googletest/1.0.1`, is another option. Once the location is established, use `svn propedit svn:externals _directory_` to set the svn:externals property on a directory in your repository. This directory won't contain the code, but be its versioned parent directory. -The command `svn propedit` will bring up your Subversion editor, making editing the long, (potentially multi-line) property simpler. This same method can be used to check out a tagged branch, by using the appropriate URL (e.g. `http://googletest.googlecode.com/svn/tags/release-1.0.1`). Additionally, the svn:externals property allows the specification of a particular revision of the trunk with the `-r_##_` option (e.g. `externals/src/googletest -r60 http://googletest.googlecode.com/svn/trunk`). +The command `svn propedit` will bring up your Subversion editor, making editing the long, (potentially multi-line) property simpler. This same method can be used to check out a tagged branch, by using the appropriate URL (e.g. `https://github.com/google/googletest/releases/tag/release-1.0.1`). Additionally, the svn:externals property allows the specification of a particular revision of the trunk with the `-r_##_` option (e.g. `externals/src/googletest -r60 http://googletest.googlecode.com/svn/trunk`). Here is an example of using the svn:externals properties on a trunk (read via `svn propget`) of a project. This value checks out a copy of Google Test into the `trunk/externals/src/googletest/` directory. @@ -90,4 +90,4 @@ The Debugger has exited with status 0. # Summary # -Unit testing is a valuable way to ensure your data model stays valid even during rapid development or refactoring. The Google Testing Framework is a great unit testing framework for C and C++ which integrates well with an Xcode development environment. \ No newline at end of file +Unit testing is a valuable way to ensure your data model stays valid even during rapid development or refactoring. The Google Testing Framework is a great unit testing framework for C and C++ which integrates well with an Xcode development environment. diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index 6883784..feb8ad6 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -154,7 +154,7 @@ c is 10 > `ASSERT_PRED*` or `EXPECT_PRED*`, please see > [this](faq#OverloadedPredicate) for how to resolve it. > 1. Currently we only provide predicate assertions of arity <= 5. If you need -> a higher-arity assertion, let [us](http://g/opensource-gtest) know. +> a higher-arity assertion, let [us](https://github.com/google/googletest/issues) know. **Availability**: Linux, Windows, Mac. @@ -382,7 +382,7 @@ Verifies that `val1` is less than, or almost equal to, `val2`. You can replace ### Asserting Using gMock Matchers -Google-developed C++ mocking framework [gMock](http://go/gmock) comes with a +Google-developed C++ mocking framework [gMock](../../googlemock) comes with a library of matchers for validating arguments passed to mock objects. A gMock *matcher* is basically a predicate that knows how to describe itself. It can be used in these assertion macros: @@ -402,17 +402,17 @@ using ::testing::StartsWith; EXPECT_THAT(Foo(), StartsWith("Hello")); ``` -Read this [recipe](http://go/gmockguide#using-matchers-in-gunit-assertions) in +Read this [recipe](../../googlemock/docs/CookBook.md#using-matchers-in-google-test-assertions) in the gMock Cookbook for more details. gMock has a rich set of matchers. You can do many things googletest cannot do alone with them. For a list of matchers gMock provides, read -[this](http://go/gmockguide#using-matchers). Especially useful among them are -some [protocol buffer matchers](http://go/protomatchers). It's easy to write -your [own matchers](http://go/gmockguide#NewMatchers) too. +[this](../../googlemock/docs/CookBook.md#using-matchers). Especially useful among them are +some [protocol buffer matchers](https://github.com/google/nucleus/blob/master/nucleus/testing/protocol-buffer-matchers.h). It's easy to write +your [own matchers](../../googlemock/docs/CookBook.md#writing-new-matchers-quickly) too. For example, you can use gMock's -[EqualsProto](http://cs/#piper///depot/google3/testing/base/public/gmock_utils/protocol-buffer-matchers.h) +[EqualsProto](https://github.com/google/nucleus/blob/master/nucleus/testing/protocol-buffer-matchers.h) to compare protos in your tests: ```c++ @@ -433,7 +433,7 @@ and you're ready to go. (Please read the [previous](#AssertThat) section first if you haven't.) -You can use the gMock [string matchers](http://go/gmockguide#string-matchers) +You can use the gMock [string matchers](../../googlemock/docs/CheatSheet.md#string-matchers) with `EXPECT_THAT()` or `ASSERT_THAT()` to do more string comparison tricks (sub-string, prefix, suffix, regular expression, and etc). For example, diff --git a/googletest/docs/faq.md b/googletest/docs/faq.md index dad2836..d613f7b 100644 --- a/googletest/docs/faq.md +++ b/googletest/docs/faq.md @@ -162,7 +162,7 @@ result, any in-memory side effects they incur are observable in their respective sub-processes, but not in the parent process. You can think of them as running in a parallel universe, more or less. -In particular, if you use [gMock](http://go/gmock) and the death test statement +In particular, if you use [gMock](../../googlemock) and the death test statement invokes some mock methods, the parent process will think the calls have never occurred. Therefore, you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH` macro. @@ -289,7 +289,7 @@ Please make sure you have read [this](advanced.md#how-it-works). In particular, death tests don't like having multiple threads in the parent process. So the first thing you can try is to eliminate creating threads outside -of `EXPECT_DEATH()`. For example, you may want to use [mocks](http://go/gmock) +of `EXPECT_DEATH()`. For example, you may want to use [mocks](../../googlemock) or fake objects instead of real ones in your tests. Sometimes this is impossible as some library you must use may be creating @@ -704,7 +704,7 @@ mistake in production. Such cleverness also leads to advise against the practice, and googletest doesn't provide a way to do it. In general, the recommended way to cause the code to behave differently under -test is [Dependency Injection](http://go/dependency-injection). You can inject +test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject different functionality from the test and from the production code. Since your production code doesn't link in the for-test logic at all (the [`testonly`](http://go/testonly) attribute for BUILD targets helps to ensure diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 260d50b..02dea42 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -5,8 +5,8 @@ *googletest* helps you write better C++ tests. -googletest is a testing framework developed by the [Testing -Technology](http://engdoc/eng/testing/TT/) team with Google's specific +googletest is a testing framework developed by the Testing +Technology team with Google's specific requirements and constraints in mind. No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it supports *any* kind of tests, not just unit tests. @@ -75,7 +75,7 @@ the terms: Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term :----------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- | :---------------------------------- Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case](http://glossary.istqb.org/search/test%20case) -A set of several tests related to one component | [TestCase](https://g3doc.corp.google.com/third_party/googletest/googletest/g3doc/primer.md#basic-concepts) | [TestSuite](http://glossary.istqb.org/search/test%20suite) +A set of several tests related to one component | [TestCase](#basic-concepts) | [TestSuite](http://glossary.istqb.org/search/test%20suite) ## Basic Concepts diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index dbe703b..cfe5515 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -379,7 +379,7 @@ #if GTEST_LANG_CXX11 # define GTEST_HAS_STD_TUPLE_ 1 # if defined(__clang__) -// Inspired by http://clang.llvm.org/docs/LanguageExtensions.html#__has_include +// Inspired by https://clang.llvm.org/docs/LanguageExtensions.html#include-file-checking-macros # if defined(__has_include) && !__has_include() # undef GTEST_HAS_STD_TUPLE_ # endif @@ -391,7 +391,7 @@ # elif defined(__GLIBCXX__) // Inspired by boost/config/stdlib/libstdcpp3.hpp, // http://gcc.gnu.org/gcc-4.2/changes.html and -// http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x +// https://web.archive.org/web/20140227044429/gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2) # undef GTEST_HAS_STD_TUPLE_ # endif @@ -1799,7 +1799,7 @@ class GTEST_API_ Mutex { // Initializes owner_thread_id_ and critical_section_ in static mutexes. void ThreadSafeLazyInit(); - // Per http://blogs.msdn.com/b/oldnewthing/archive/2004/02/23/78395.aspx, + // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503, // we assume that 0 is an invalid value for thread IDs. unsigned int owner_thread_id_; diff --git a/googletest/scripts/upload.py b/googletest/scripts/upload.py index 81e8e04..c852e4c 100755 --- a/googletest/scripts/upload.py +++ b/googletest/scripts/upload.py @@ -242,7 +242,7 @@ class AbstractRpcServer(object): The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user - (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). + (see https://developers.google.com/identity/protocols/AuthForInstalledApps). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. @@ -506,7 +506,7 @@ def EncodeMultipartFormData(fields, files): (content_type, body) ready for httplib.HTTP instance. Source: - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 + https://web.archive.org/web/20160116052001/code.activestate.com/recipes/146306 """ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' @@ -807,7 +807,7 @@ class SubversionVCS(VersionControlSystem): # svn cat translates keywords but svn diff doesn't. As a result of this # behavior patching.PatchChunks() fails with a chunk mismatch error. # This part was originally written by the Review Board development team - # who had the same problem (http://reviews.review-board.org/r/276/). + # who had the same problem (https://reviews.reviewboard.org/r/276/). # Mapping of keywords to known aliases svn_keywords = { # Standard keywords @@ -860,7 +860,7 @@ class SubversionVCS(VersionControlSystem): status_lines = status.splitlines() # If file is in a cl, the output will begin with # "\n--- Changelist 'cl_name':\n". See - # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt + # https://web.archive.org/web/20090918234815/svn.collab.net/repos/svn/trunk/notes/changelist-design.txt if (len(status_lines) == 3 and not status_lines[0] and status_lines[1].startswith("--- Changelist")): diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index f8a0ad6..5fbb08b 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -264,7 +264,7 @@ Mutex::~Mutex() { // to clean them up. // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires // nothing to clean it up but is available only on Vista and later. - // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx + // https://docs.microsoft.com/en-us/windows/desktop/Sync/slim-reader-writer--srw--locks if (type_ == kDynamic) { ::DeleteCriticalSection(critical_section_); delete critical_section_; diff --git a/googletest/test/gtest-death-test_test.cc b/googletest/test/gtest-death-test_test.cc index 37261cb..9d8f13c 100644 --- a/googletest/test/gtest-death-test_test.cc +++ b/googletest/test/gtest-death-test_test.cc @@ -784,7 +784,7 @@ static void TestExitMacros() { // Of all signals effects on the process exit code, only those of SIGABRT // are documented on Windows. - // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx. + // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c. EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar"; # elif !GTEST_OS_FUCHSIA diff --git a/googletest/xcode/Config/DebugProject.xcconfig b/googletest/xcode/Config/DebugProject.xcconfig index 3d68157..645701e 100644 --- a/googletest/xcode/Config/DebugProject.xcconfig +++ b/googletest/xcode/Config/DebugProject.xcconfig @@ -5,7 +5,7 @@ // examples. It is set in the "Based On:" dropdown in the "Project" info // dialog. // This file is based on the Xcode Configuration files in: -// http://code.google.com/p/google-toolbox-for-mac/ +// https://github.com/google/google-toolbox-for-mac // #include "General.xcconfig" diff --git a/googletest/xcode/Config/FrameworkTarget.xcconfig b/googletest/xcode/Config/FrameworkTarget.xcconfig index 357b1c8..77081fb 100644 --- a/googletest/xcode/Config/FrameworkTarget.xcconfig +++ b/googletest/xcode/Config/FrameworkTarget.xcconfig @@ -4,7 +4,7 @@ // These are Framework target settings for the gtest framework and examples. It // is set in the "Based On:" dropdown in the "Target" info dialog. // This file is based on the Xcode Configuration files in: -// http://code.google.com/p/google-toolbox-for-mac/ +// https://github.com/google/google-toolbox-for-mac // // Dynamic libs need to be position independent diff --git a/googletest/xcode/Config/General.xcconfig b/googletest/xcode/Config/General.xcconfig index f23e322..1aba486 100644 --- a/googletest/xcode/Config/General.xcconfig +++ b/googletest/xcode/Config/General.xcconfig @@ -4,7 +4,7 @@ // These are General configuration settings for the gtest framework and // examples. // This file is based on the Xcode Configuration files in: -// http://code.google.com/p/google-toolbox-for-mac/ +// https://github.com/google/google-toolbox-for-mac // // Build for PPC and Intel, 32- and 64-bit diff --git a/googletest/xcode/Config/ReleaseProject.xcconfig b/googletest/xcode/Config/ReleaseProject.xcconfig index 5349f0a..df9a38f 100644 --- a/googletest/xcode/Config/ReleaseProject.xcconfig +++ b/googletest/xcode/Config/ReleaseProject.xcconfig @@ -5,7 +5,7 @@ // and examples. It is set in the "Based On:" dropdown in the "Project" info // dialog. // This file is based on the Xcode Configuration files in: -// http://code.google.com/p/google-toolbox-for-mac/ +// https://github.com/google/google-toolbox-for-mac // #include "General.xcconfig" diff --git a/googletest/xcode/Config/StaticLibraryTarget.xcconfig b/googletest/xcode/Config/StaticLibraryTarget.xcconfig index 3922fa5..d2424fe 100644 --- a/googletest/xcode/Config/StaticLibraryTarget.xcconfig +++ b/googletest/xcode/Config/StaticLibraryTarget.xcconfig @@ -4,7 +4,7 @@ // These are static library target settings for libgtest.a. It // is set in the "Based On:" dropdown in the "Target" info dialog. // This file is based on the Xcode Configuration files in: -// http://code.google.com/p/google-toolbox-for-mac/ +// https://github.com/google/google-toolbox-for-mac // // Static libs can be included in bundles so make them position independent -- cgit v0.12 From 984cba30ed10622122c12960b4914656fc770e04 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 27 Jul 2018 11:15:08 -0400 Subject: Formatting changes for automatic code management --- googlemock/include/gmock/gmock-actions.h | 2 ++ googlemock/include/gmock/gmock-cardinalities.h | 2 ++ googlemock/include/gmock/gmock-generated-actions.h | 2 ++ googlemock/include/gmock/gmock-generated-actions.h.pump | 2 ++ googlemock/include/gmock/gmock-generated-function-mockers.h | 2 ++ googlemock/include/gmock/gmock-generated-function-mockers.h.pump | 4 +++- googlemock/include/gmock/gmock-generated-matchers.h | 2 ++ googlemock/include/gmock/gmock-generated-matchers.h.pump | 2 ++ googlemock/include/gmock/gmock-generated-nice-strict.h | 2 ++ googlemock/include/gmock/gmock-generated-nice-strict.h.pump | 2 ++ googlemock/include/gmock/gmock-matchers.h | 2 ++ googlemock/include/gmock/gmock-more-actions.h | 2 ++ googlemock/include/gmock/gmock-more-matchers.h | 2 ++ googlemock/include/gmock/gmock-spec-builders.h | 2 ++ googlemock/include/gmock/gmock.h | 2 ++ googlemock/include/gmock/internal/custom/gmock-generated-actions.h | 2 ++ .../include/gmock/internal/custom/gmock-generated-actions.h.pump | 2 ++ googlemock/include/gmock/internal/custom/gmock-matchers.h | 2 ++ googlemock/include/gmock/internal/custom/gmock-port.h | 2 ++ googlemock/include/gmock/internal/gmock-generated-internal-utils.h | 2 ++ .../include/gmock/internal/gmock-generated-internal-utils.h.pump | 2 ++ googlemock/include/gmock/internal/gmock-internal-utils.h | 2 ++ googlemock/include/gmock/internal/gmock-port.h | 2 ++ googletest/include/gtest/gtest-death-test.h | 1 + googletest/include/gtest/gtest-message.h | 2 ++ googletest/include/gtest/gtest-param-test.h | 1 + googletest/include/gtest/gtest-param-test.h.pump | 1 + googletest/include/gtest/gtest-printers.h | 2 ++ googletest/include/gtest/gtest-spi.h | 2 ++ googletest/include/gtest/gtest-test-part.h | 2 ++ googletest/include/gtest/gtest-typed-test.h | 2 ++ googletest/include/gtest/gtest.h | 2 ++ googletest/include/gtest/gtest_pred_impl.h | 2 ++ googletest/include/gtest/gtest_prod.h | 1 + googletest/include/gtest/internal/gtest-death-test-internal.h | 1 + googletest/include/gtest/internal/gtest-filepath.h | 2 ++ googletest/include/gtest/internal/gtest-internal.h | 2 ++ googletest/include/gtest/internal/gtest-linked_ptr.h | 2 ++ googletest/include/gtest/internal/gtest-param-util-generated.h | 2 ++ googletest/include/gtest/internal/gtest-param-util-generated.h.pump | 2 ++ googletest/include/gtest/internal/gtest-param-util.h | 2 ++ googletest/include/gtest/internal/gtest-port.h | 2 ++ googletest/include/gtest/internal/gtest-string.h | 2 ++ googletest/include/gtest/internal/gtest-tuple.h | 2 ++ googletest/include/gtest/internal/gtest-tuple.h.pump | 2 ++ googletest/include/gtest/internal/gtest-type-util.h | 2 ++ googletest/include/gtest/internal/gtest-type-util.h.pump | 2 ++ 47 files changed, 90 insertions(+), 1 deletion(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index a2784f6..42648ad 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -33,6 +33,8 @@ // // This file implements some commonly used actions. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/googlemock/include/gmock/gmock-cardinalities.h b/googlemock/include/gmock/gmock-cardinalities.h index fc315f9..2ce16af 100644 --- a/googlemock/include/gmock/gmock-cardinalities.h +++ b/googlemock/include/gmock/gmock-cardinalities.h @@ -35,6 +35,8 @@ // cardinalities can be defined by the user implementing the // CardinalityInterface interface if necessary. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h index 7728d74..4ce7d35 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h +++ b/googlemock/include/gmock/gmock-generated-actions.h @@ -37,6 +37,8 @@ // // This file implements some commonly used variadic actions. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump index 8bafa47..4ec6679 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/gmock-generated-actions.h.pump @@ -39,6 +39,8 @@ $$}} This meta comment fixes auto-indentation in editors. // // This file implements some commonly used variadic actions. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h b/googlemock/include/gmock/gmock-generated-function-mockers.h index b8bf7a5..0474c89 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h @@ -37,6 +37,8 @@ // // This file implements function mockers of various arities. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump index 6426d9a..f6e1781 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump @@ -38,6 +38,8 @@ $var n = 10 $$ The maximum arity we support. // // This file implements function mockers of various arities. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ @@ -139,7 +141,7 @@ const MockType* AdjustConstness_const(const MockType* mock) { return mock; } -// Removes const from and returns the given pointer; this is a helper for the +// Removes const from and returns the given pointer; this is a helper for the // expectation setter method for parameterless matchers. template MockType* AdjustConstness_(const MockType* mock) { diff --git a/googlemock/include/gmock/gmock-generated-matchers.h b/googlemock/include/gmock/gmock-generated-matchers.h index 21af61b..0d46d23 100644 --- a/googlemock/include/gmock/gmock-generated-matchers.h +++ b/googlemock/include/gmock/gmock-generated-matchers.h @@ -35,6 +35,8 @@ // // This file implements some commonly used variadic matchers. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ diff --git a/googlemock/include/gmock/gmock-generated-matchers.h.pump b/googlemock/include/gmock/gmock-generated-matchers.h.pump index 4b62844..9fe0fd7 100644 --- a/googlemock/include/gmock/gmock-generated-matchers.h.pump +++ b/googlemock/include/gmock/gmock-generated-matchers.h.pump @@ -37,6 +37,8 @@ $$ }} This line fixes auto-indentation of the following code in Emacs. // // This file implements some commonly used variadic matchers. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ diff --git a/googlemock/include/gmock/gmock-generated-nice-strict.h b/googlemock/include/gmock/gmock-generated-nice-strict.h index 8e56873..96d6f39 100644 --- a/googlemock/include/gmock/gmock-generated-nice-strict.h +++ b/googlemock/include/gmock/gmock-generated-nice-strict.h @@ -63,6 +63,8 @@ // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT // supported. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ diff --git a/googlemock/include/gmock/gmock-generated-nice-strict.h.pump b/googlemock/include/gmock/gmock-generated-nice-strict.h.pump index 2f443ae..7c2bf36 100644 --- a/googlemock/include/gmock/gmock-generated-nice-strict.h.pump +++ b/googlemock/include/gmock/gmock-generated-nice-strict.h.pump @@ -64,6 +64,8 @@ $var n = 10 $$ The maximum arity we support. // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT // supported. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index eb09613..adf4999 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -35,6 +35,8 @@ // matchers can be defined by the user implementing the // MatcherInterface interface if necessary. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ diff --git a/googlemock/include/gmock/gmock-more-actions.h b/googlemock/include/gmock/gmock-more-actions.h index 3d387b6..1106818 100644 --- a/googlemock/include/gmock/gmock-more-actions.h +++ b/googlemock/include/gmock/gmock-more-actions.h @@ -33,6 +33,8 @@ // // This file implements some actions that depend on gmock-generated-actions.h. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ diff --git a/googlemock/include/gmock/gmock-more-matchers.h b/googlemock/include/gmock/gmock-more-matchers.h index 6d810eb..6c6b3e3 100644 --- a/googlemock/include/gmock/gmock-more-matchers.h +++ b/googlemock/include/gmock/gmock-more-matchers.h @@ -36,6 +36,8 @@ // Note that tests are implemented in gmock-matchers_test.cc rather than // gmock-more-matchers-test.cc. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_GMOCK_MORE_MATCHERS_H_ #define GMOCK_GMOCK_MORE_MATCHERS_H_ diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index 090cff4..9670b59 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -57,6 +57,8 @@ // where all clauses are optional, and .InSequence()/.After()/ // .WillOnce() can appear any number of times. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ diff --git a/googlemock/include/gmock/gmock.h b/googlemock/include/gmock/gmock.h index 6ccb118..6330294 100644 --- a/googlemock/include/gmock/gmock.h +++ b/googlemock/include/gmock/gmock.h @@ -33,6 +33,8 @@ // // This is the main header file a user should include. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_H_ diff --git a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h index 7dc3b1a..92d910c 100644 --- a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h +++ b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h @@ -2,6 +2,8 @@ // pump.py gmock-generated-actions.h.pump // DO NOT EDIT BY HAND!!! +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ diff --git a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump index 03cfd8c..67c221f 100644 --- a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump @@ -4,6 +4,8 @@ $$ it to callback-actions.h. $$ $var max_callback_arity = 5 $$}} This meta comment fixes auto-indentation in editors. + +// GOOGLETEST_CM0002 DO NOT DELETE #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ diff --git a/googlemock/include/gmock/internal/custom/gmock-matchers.h b/googlemock/include/gmock/internal/custom/gmock-matchers.h index af8240e..b9b7e3f 100644 --- a/googlemock/include/gmock/internal/custom/gmock-matchers.h +++ b/googlemock/include/gmock/internal/custom/gmock-matchers.h @@ -33,6 +33,8 @@ // // Adds google3 callback support to CallableTraits. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ diff --git a/googlemock/include/gmock/internal/custom/gmock-port.h b/googlemock/include/gmock/internal/custom/gmock-port.h index 9ce8bfe..ad9ae36 100644 --- a/googlemock/include/gmock/internal/custom/gmock-port.h +++ b/googlemock/include/gmock/internal/custom/gmock-port.h @@ -40,6 +40,8 @@ // // ** Custom implementation starts here ** +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ diff --git a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h index cd94d64..c9bfbc8 100644 --- a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h @@ -38,6 +38,8 @@ // This file contains template meta-programming utility classes needed // for implementing Google Mock. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ diff --git a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump index 800af17..f13151b 100644 --- a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump +++ b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump @@ -39,6 +39,8 @@ $var n = 10 $$ The maximum arity we support. // This file contains template meta-programming utility classes needed // for implementing Google Mock. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index c5841ab..e0846d9 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -35,6 +35,8 @@ // Mock. They are subject to change without notice, so please DO NOT // USE THEM IN USER CODE. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ diff --git a/googlemock/include/gmock/internal/gmock-port.h b/googlemock/include/gmock/internal/gmock-port.h index cb37f26..79f4366 100644 --- a/googlemock/include/gmock/internal/gmock-port.h +++ b/googlemock/include/gmock/internal/gmock-port.h @@ -36,6 +36,8 @@ // end with _ are part of Google Mock's public API and can be used by // code outside Google Mock. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h index 53f11d4..8add8c0 100644 --- a/googletest/include/gtest/gtest-death-test.h +++ b/googletest/include/gtest/gtest-death-test.h @@ -34,6 +34,7 @@ // This header file defines the public API for death tests. It is // #included by gtest.h so a user doesn't need to include this // directly. +// GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h index d7266ba..3e3870c 100644 --- a/googletest/include/gtest/gtest-message.h +++ b/googletest/include/gtest/gtest-message.h @@ -43,6 +43,8 @@ // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user // program! +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index 8993c1c..3ea3338 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -38,6 +38,7 @@ // // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // +// GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ diff --git a/googletest/include/gtest/gtest-param-test.h.pump b/googletest/include/gtest/gtest-param-test.h.pump index 7b7243f..4dac9f2 100644 --- a/googletest/include/gtest/gtest-param-test.h.pump +++ b/googletest/include/gtest/gtest-param-test.h.pump @@ -37,6 +37,7 @@ $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. // // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // +// GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index 66d54b9..57eb5ae 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -96,6 +96,8 @@ // being defined as many user-defined container types don't have // value_type. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ #define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ diff --git a/googletest/include/gtest/gtest-spi.h b/googletest/include/gtest/gtest-spi.h index 0e5c10c..2a48cca 100644 --- a/googletest/include/gtest/gtest-spi.h +++ b/googletest/include/gtest/gtest-spi.h @@ -32,6 +32,8 @@ // Utilities for testing Google Test itself and code that uses Google Test // (e.g. frameworks built on top of Google Test). +GOOGLETEST_CM0004 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ diff --git a/googletest/include/gtest/gtest-test-part.h b/googletest/include/gtest/gtest-test-part.h index 77eb844..301a012 100644 --- a/googletest/include/gtest/gtest-test-part.h +++ b/googletest/include/gtest/gtest-test-part.h @@ -30,6 +30,8 @@ // Author: mheule@google.com (Markus Heule) // +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ #define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h index 759d1db..00925af 100644 --- a/googletest/include/gtest/gtest-typed-test.h +++ b/googletest/include/gtest/gtest-typed-test.h @@ -29,6 +29,8 @@ // // Author: wan@google.com (Zhanyong Wan) +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index 686750e..a6c674b 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -48,6 +48,8 @@ // registration from Barthelemy Dagenais' (barthelemy@prologique.com) // easyUnit framework. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_H_ diff --git a/googletest/include/gtest/gtest_pred_impl.h b/googletest/include/gtest/gtest_pred_impl.h index c8be230..0c1105c 100644 --- a/googletest/include/gtest/gtest_pred_impl.h +++ b/googletest/include/gtest/gtest_pred_impl.h @@ -32,6 +32,8 @@ // // Implements a family of generic predicate assertion macros. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ diff --git a/googletest/include/gtest/gtest_prod.h b/googletest/include/gtest/gtest_prod.h index 89314f4..21e211e 100644 --- a/googletest/include/gtest/gtest_prod.h +++ b/googletest/include/gtest/gtest_prod.h @@ -30,6 +30,7 @@ // Author: wan@google.com (Zhanyong Wan) // // Google C++ Testing and Mocking Framework definitions useful in production code. +GOOGLETEST_CM0003 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ #define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h index 949c429..719aee6 100644 --- a/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -32,6 +32,7 @@ // // This header file defines internal utilities needed for implementing // death tests. They are subject to change without notice. +// GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ diff --git a/googletest/include/gtest/internal/gtest-filepath.h b/googletest/include/gtest/internal/gtest-filepath.h index 406597a..e18fe45 100644 --- a/googletest/include/gtest/internal/gtest-filepath.h +++ b/googletest/include/gtest/internal/gtest-filepath.h @@ -36,6 +36,8 @@ // This file is #included in gtest/internal/gtest-internal.h. // Do not include this header file separately! +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index fc65b1f..45192e2 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -33,6 +33,8 @@ // This header file declares functions and macros used internally by // Google Test. They are subject to change without notice. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ diff --git a/googletest/include/gtest/internal/gtest-linked_ptr.h b/googletest/include/gtest/internal/gtest-linked_ptr.h index 3602942..8e1caa0 100644 --- a/googletest/include/gtest/internal/gtest-linked_ptr.h +++ b/googletest/include/gtest/internal/gtest-linked_ptr.h @@ -65,6 +65,8 @@ // TODO(wan@google.com): rename this to safe_linked_ptr to avoid // confusion with normal linked_ptr. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ diff --git a/googletest/include/gtest/internal/gtest-param-util-generated.h b/googletest/include/gtest/internal/gtest-param-util-generated.h index dcf90c2..ef22e89 100644 --- a/googletest/include/gtest/internal/gtest-param-util-generated.h +++ b/googletest/include/gtest/internal/gtest-param-util-generated.h @@ -43,6 +43,8 @@ // by the maximum arity of the implementation of tuple which is // currently set at 10. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ diff --git a/googletest/include/gtest/internal/gtest-param-util-generated.h.pump b/googletest/include/gtest/internal/gtest-param-util-generated.h.pump index d65086a..856caba 100644 --- a/googletest/include/gtest/internal/gtest-param-util-generated.h.pump +++ b/googletest/include/gtest/internal/gtest-param-util-generated.h.pump @@ -42,6 +42,8 @@ $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. // by the maximum arity of the implementation of tuple which is // currently set at $maxtuple. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h index 3c80863..a69d5de 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -31,6 +31,8 @@ // Type and function utilities for implementing parameterized tests. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index dbe703b..1c0654c 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -40,6 +40,8 @@ // files are expected to #include this. Therefore, it cannot #include // any other Google Test header. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h index 64da26c..1d2436c 100644 --- a/googletest/include/gtest/internal/gtest-string.h +++ b/googletest/include/gtest/internal/gtest-string.h @@ -37,6 +37,8 @@ // This header file is #included by gtest-internal.h. // It should not be #included by other files. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ diff --git a/googletest/include/gtest/internal/gtest-tuple.h b/googletest/include/gtest/internal/gtest-tuple.h index e9b4053..e64cede 100644 --- a/googletest/include/gtest/internal/gtest-tuple.h +++ b/googletest/include/gtest/internal/gtest-tuple.h @@ -35,6 +35,8 @@ // Implements a subset of TR1 tuple needed by Google Test and Google Mock. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ diff --git a/googletest/include/gtest/internal/gtest-tuple.h.pump b/googletest/include/gtest/internal/gtest-tuple.h.pump index 429ddfe..2736360 100644 --- a/googletest/include/gtest/internal/gtest-tuple.h.pump +++ b/googletest/include/gtest/internal/gtest-tuple.h.pump @@ -34,6 +34,8 @@ $$ This meta comment fixes auto-indentation in Emacs. }} // Implements a subset of TR1 tuple needed by Google Test and Google Mock. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h index 282b81f..2681dbb 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h +++ b/googletest/include/gtest/internal/gtest-type-util.h @@ -41,6 +41,8 @@ // Please contact googletestframework@googlegroups.com if you need // more. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ diff --git a/googletest/include/gtest/internal/gtest-type-util.h.pump b/googletest/include/gtest/internal/gtest-type-util.h.pump index eaa8880..8897795 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h.pump +++ b/googletest/include/gtest/internal/gtest-type-util.h.pump @@ -39,6 +39,8 @@ $var n = 50 $$ Maximum length of type lists we want to support. // Please contact googletestframework@googlegroups.com if you need // more. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ -- cgit v0.12 From ec13264af4595af8bae9be425ecf09ebf588dce3 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 27 Jul 2018 15:05:20 -0400 Subject: added missing comments --- googletest/include/gtest/gtest-spi.h | 2 +- googletest/include/gtest/gtest_prod.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/googletest/include/gtest/gtest-spi.h b/googletest/include/gtest/gtest-spi.h index 2a48cca..c21b029 100644 --- a/googletest/include/gtest/gtest-spi.h +++ b/googletest/include/gtest/gtest-spi.h @@ -32,7 +32,7 @@ // Utilities for testing Google Test itself and code that uses Google Test // (e.g. frameworks built on top of Google Test). -GOOGLETEST_CM0004 DO NOT DELETE +// GOOGLETEST_CM0004 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ diff --git a/googletest/include/gtest/gtest_prod.h b/googletest/include/gtest/gtest_prod.h index 21e211e..71377f8 100644 --- a/googletest/include/gtest/gtest_prod.h +++ b/googletest/include/gtest/gtest_prod.h @@ -30,7 +30,7 @@ // Author: wan@google.com (Zhanyong Wan) // // Google C++ Testing and Mocking Framework definitions useful in production code. -GOOGLETEST_CM0003 DO NOT DELETE +// GOOGLETEST_CM0003 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ #define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ -- cgit v0.12 From b7cb1bc6f9d63df7ec9c9b0897de047a8c728615 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 30 Jul 2018 13:31:46 -0400 Subject: small tweaks, OSS merge cl 206357486 --- googletest/src/gtest_main.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/src/gtest_main.cc b/googletest/src/gtest_main.cc index 5e9c94c..f039d00 100644 --- a/googletest/src/gtest_main.cc +++ b/googletest/src/gtest_main.cc @@ -32,7 +32,7 @@ #include "gtest/gtest.h" GTEST_API_ int main(int argc, char **argv) { - printf("Running main() from gtest_main.cc\n"); + printf("Running main() from %s\n", __FILE__); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } -- cgit v0.12 From 539ee4bc549846e3bd98b77f85d0aff8410ef8c0 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 11:07:22 -0400 Subject: Formatting changes and upstreaming one test --- googlemock/test/gmock_leak_test.py | 2 - googlemock/test/gmock_output_test.py | 1 - googletest/test/BUILD.bazel | 8 ++ .../test/gtest_test_macro_stack_footprint_test.cc | 90 ++++++++++++++++++++++ 4 files changed, 98 insertions(+), 3 deletions(-) create mode 100644 googletest/test/gtest_test_macro_stack_footprint_test.cc diff --git a/googlemock/test/gmock_leak_test.py b/googlemock/test/gmock_leak_test.py index 997680c..a2fee4b 100755 --- a/googlemock/test/gmock_leak_test.py +++ b/googlemock/test/gmock_leak_test.py @@ -33,10 +33,8 @@ __author__ = 'wan@google.com (Zhanyong Wan)' - import gmock_test_utils - PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_') TEST_WITH_EXPECT_CALL = [PROGRAM_PATH, '--gtest_filter=*ExpectCall*'] TEST_WITH_ON_CALL = [PROGRAM_PATH, '--gtest_filter=*OnCall*'] diff --git a/googlemock/test/gmock_output_test.py b/googlemock/test/gmock_output_test.py index 9d73d57..8f57d46 100755 --- a/googlemock/test/gmock_output_test.py +++ b/googlemock/test/gmock_output_test.py @@ -43,7 +43,6 @@ __author__ = 'wan@google.com (Zhanyong Wan)' import os import re import sys - import gmock_test_utils diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 405feee..6888e4c 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -97,6 +97,14 @@ cc_test( deps = ["//:gtest_main"], ) + +cc_test( + name = "gtest_test_macro_stack_footprint_test", + size = "small", + srcs = ["gtest_test_macro_stack_footprint_test.cc"], + deps = ["//:gtest"], +) + #These googletest tests have their own main() cc_test( name = "gtest-listener_test", diff --git a/googletest/test/gtest_test_macro_stack_footprint_test.cc b/googletest/test/gtest_test_macro_stack_footprint_test.cc new file mode 100644 index 0000000..48958b8 --- /dev/null +++ b/googletest/test/gtest_test_macro_stack_footprint_test.cc @@ -0,0 +1,90 @@ +// Copyright 2013, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// Each TEST() expands to some static registration logic. GCC puts all +// such static initialization logic for a translation unit in a common, +// internal function. Since Google's build system restricts how much +// stack space a function can use, there's a limit on how many TEST()s +// one can put in a single C++ test file. This test ensures that a large +// number of TEST()s can be defined in the same translation unit. + +#include "gtest/gtest.h" + +// This macro defines 10 dummy tests. +#define TEN_TESTS_(test_case_name) \ + TEST(test_case_name, T0) {} \ + TEST(test_case_name, T1) {} \ + TEST(test_case_name, T2) {} \ + TEST(test_case_name, T3) {} \ + TEST(test_case_name, T4) {} \ + TEST(test_case_name, T5) {} \ + TEST(test_case_name, T6) {} \ + TEST(test_case_name, T7) {} \ + TEST(test_case_name, T8) {} \ + TEST(test_case_name, T9) {} + +// This macro defines 100 dummy tests. +#define HUNDRED_TESTS_(test_case_name_prefix) \ + TEN_TESTS_(test_case_name_prefix ## 0) \ + TEN_TESTS_(test_case_name_prefix ## 1) \ + TEN_TESTS_(test_case_name_prefix ## 2) \ + TEN_TESTS_(test_case_name_prefix ## 3) \ + TEN_TESTS_(test_case_name_prefix ## 4) \ + TEN_TESTS_(test_case_name_prefix ## 5) \ + TEN_TESTS_(test_case_name_prefix ## 6) \ + TEN_TESTS_(test_case_name_prefix ## 7) \ + TEN_TESTS_(test_case_name_prefix ## 8) \ + TEN_TESTS_(test_case_name_prefix ## 9) + +// This macro defines 1000 dummy tests. +#define THOUSAND_TESTS_(test_case_name_prefix) \ + HUNDRED_TESTS_(test_case_name_prefix ## 0) \ + HUNDRED_TESTS_(test_case_name_prefix ## 1) \ + HUNDRED_TESTS_(test_case_name_prefix ## 2) \ + HUNDRED_TESTS_(test_case_name_prefix ## 3) \ + HUNDRED_TESTS_(test_case_name_prefix ## 4) \ + HUNDRED_TESTS_(test_case_name_prefix ## 5) \ + HUNDRED_TESTS_(test_case_name_prefix ## 6) \ + HUNDRED_TESTS_(test_case_name_prefix ## 7) \ + HUNDRED_TESTS_(test_case_name_prefix ## 8) \ + HUNDRED_TESTS_(test_case_name_prefix ## 9) + +// Ensures that we can define 1000 TEST()s in the same translation +// unit. +THOUSAND_TESTS_(T) + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + + // We don't actually need to run the dummy tests - the purpose is to + // ensure that they compile. + return 0; +} -- cgit v0.12 From 6324796be1507712d8b6ad5f4b430d20c33beed6 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 11:28:24 -0400 Subject: googletest-output-test changes --- googletest/test/BUILD.bazel | 13 +- .../test/googletest-output-test-golden-lin.txt | 997 ++++++++++++++++++ googletest/test/googletest-output-test.py | 350 +++++++ googletest/test/googletest-output-test_.cc | 1067 ++++++++++++++++++++ googletest/test/gtest_output_test.py | 350 ------- googletest/test/gtest_output_test_.cc | 1067 -------------------- googletest/test/gtest_output_test_golden_lin.txt | 997 ------------------ 7 files changed, 2421 insertions(+), 2420 deletions(-) create mode 100644 googletest/test/googletest-output-test-golden-lin.txt create mode 100755 googletest/test/googletest-output-test.py create mode 100644 googletest/test/googletest-output-test_.cc delete mode 100755 googletest/test/gtest_output_test.py delete mode 100644 googletest/test/gtest_output_test_.cc delete mode 100644 googletest/test/gtest_output_test_golden_lin.txt diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 6888e4c..9f190c0 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -174,23 +174,24 @@ py_test( ) cc_binary( - name = "gtest_output_test_", + name = "googletest-output-test_", testonly = 1, - srcs = ["gtest_output_test_.cc"], + srcs = ["googletest-output-test_.cc"], deps = ["//:gtest"], ) + py_test( - name = "gtest_output_test", + name = "googletest-output-test", size = "small", - srcs = ["gtest_output_test.py"], + srcs = ["googletest-output-test.py"], args = select({ ":has_absl": [], "//conditions:default": ["--no_stacktrace_support"], }), data = [ - "gtest_output_test_golden_lin.txt", - ":gtest_output_test_", + "googletest-output-test-golden-lin.txt", + ":googletest-output-test_", ], deps = [":gtest_test_utils"], ) diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt new file mode 100644 index 0000000..b0c5189 --- /dev/null +++ b/googletest/test/googletest-output-test-golden-lin.txt @@ -0,0 +1,997 @@ +The non-test part of the code is expected to have 2 failures. + +googletest-output-test_.cc:#: Failure +Value of: false + Actual: false +Expected: true +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 2 + 3 +Stack trace: (omitted) + +[==========] Running 68 tests from 30 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 +[----------] 2 tests from NonfatalFailureTest +[ RUN ] NonfatalFailureTest.EscapesStringOperands +googletest-output-test_.cc:#: Failure +Expected equality of these values: + kGoldenString + Which is: "\"Line" + actual + Which is: "actual \"string\"" +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Expected equality of these values: + golden + Which is: "\"Line" + actual + Which is: "actual \"string\"" +Stack trace: (omitted) + +[ FAILED ] NonfatalFailureTest.EscapesStringOperands +[ RUN ] NonfatalFailureTest.DiffForLongStrings +googletest-output-test_.cc:#: Failure +Expected equality of these values: + golden_str + Which is: "\"Line\0 1\"\nLine 2" + "Line 2" +With diff: +@@ -1,2 @@ +-\"Line\0 1\" + Line 2 + +Stack trace: (omitted) + +[ FAILED ] NonfatalFailureTest.DiffForLongStrings +[----------] 3 tests from FatalFailureTest +[ RUN ] FatalFailureTest.FatalFailureInSubroutine +(expecting a failure that x should be 1) +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + x + Which is: 2 +Stack trace: (omitted) + +[ FAILED ] FatalFailureTest.FatalFailureInSubroutine +[ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine +(expecting a failure that x should be 1) +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + x + Which is: 2 +Stack trace: (omitted) + +[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine +[ RUN ] FatalFailureTest.NonfatalFailureInSubroutine +(expecting a failure on false) +googletest-output-test_.cc:#: Failure +Value of: false + Actual: false +Expected: true +Stack trace: (omitted) + +[ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine +[----------] 1 test from LoggingTest +[ RUN ] LoggingTest.InterleavingLoggingAndAssertions +(expecting 2 failures on (3) >= (a[i])) +i == 0 +i == 1 +googletest-output-test_.cc:#: Failure +Expected: (3) >= (a[i]), actual: 3 vs 9 +Stack trace: (omitted) + +i == 2 +i == 3 +googletest-output-test_.cc:#: Failure +Expected: (3) >= (a[i]), actual: 3 vs 6 +Stack trace: (omitted) + +[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions +[----------] 7 tests from SCOPED_TRACETest +[ RUN ] SCOPED_TRACETest.AcceptedValues +googletest-output-test_.cc:#: Failure +Failed +Just checking that all these values work fine. +Google Test trace: +googletest-output-test_.cc:#: (null) +googletest-output-test_.cc:#: 1337 +googletest-output-test_.cc:#: std::string +googletest-output-test_.cc:#: literal string +Stack trace: (omitted) + +[ FAILED ] SCOPED_TRACETest.AcceptedValues +[ RUN ] SCOPED_TRACETest.ObeysScopes +(expected to fail) +googletest-output-test_.cc:#: Failure +Failed +This failure is expected, and shouldn't have a trace. +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +This failure is expected, and should have a trace. +Google Test trace: +googletest-output-test_.cc:#: Expected trace +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +This failure is expected, and shouldn't have a trace. +Stack trace: (omitted) + +[ FAILED ] SCOPED_TRACETest.ObeysScopes +[ RUN ] SCOPED_TRACETest.WorksInLoop +(expected to fail) +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 2 + n + Which is: 1 +Google Test trace: +googletest-output-test_.cc:#: i = 1 +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + n + Which is: 2 +Google Test trace: +googletest-output-test_.cc:#: i = 2 +Stack trace: (omitted) + +[ FAILED ] SCOPED_TRACETest.WorksInLoop +[ RUN ] SCOPED_TRACETest.WorksInSubroutine +(expected to fail) +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 2 + n + Which is: 1 +Google Test trace: +googletest-output-test_.cc:#: n = 1 +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + n + Which is: 2 +Google Test trace: +googletest-output-test_.cc:#: n = 2 +Stack trace: (omitted) + +[ FAILED ] SCOPED_TRACETest.WorksInSubroutine +[ RUN ] SCOPED_TRACETest.CanBeNested +(expected to fail) +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + n + Which is: 2 +Google Test trace: +googletest-output-test_.cc:#: n = 2 +googletest-output-test_.cc:#: +Stack trace: (omitted) + +[ FAILED ] SCOPED_TRACETest.CanBeNested +[ RUN ] SCOPED_TRACETest.CanBeRepeated +(expected to fail) +googletest-output-test_.cc:#: Failure +Failed +This failure is expected, and should contain trace point A. +Google Test trace: +googletest-output-test_.cc:#: A +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +This failure is expected, and should contain trace point A and B. +Google Test trace: +googletest-output-test_.cc:#: B +googletest-output-test_.cc:#: A +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +This failure is expected, and should contain trace point A, B, and C. +Google Test trace: +googletest-output-test_.cc:#: C +googletest-output-test_.cc:#: B +googletest-output-test_.cc:#: A +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +This failure is expected, and should contain trace point A, B, and D. +Google Test trace: +googletest-output-test_.cc:#: D +googletest-output-test_.cc:#: B +googletest-output-test_.cc:#: A +Stack trace: (omitted) + +[ FAILED ] SCOPED_TRACETest.CanBeRepeated +[ RUN ] SCOPED_TRACETest.WorksConcurrently +(expecting 6 failures) +googletest-output-test_.cc:#: Failure +Failed +Expected failure #1 (in thread B, only trace B alive). +Google Test trace: +googletest-output-test_.cc:#: Trace B +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #2 (in thread A, trace A & B both alive). +Google Test trace: +googletest-output-test_.cc:#: Trace A +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #3 (in thread B, trace A & B both alive). +Google Test trace: +googletest-output-test_.cc:#: Trace B +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #4 (in thread B, only trace A alive). +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #5 (in thread A, only trace A alive). +Google Test trace: +googletest-output-test_.cc:#: Trace A +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #6 (in thread A, no trace alive). +Stack trace: (omitted) + +[ FAILED ] SCOPED_TRACETest.WorksConcurrently +[----------] 1 test from ScopedTraceTest +[ RUN ] ScopedTraceTest.WithExplicitFileAndLine +googletest-output-test_.cc:#: Failure +Failed +Check that the trace is attached to a particular location. +Google Test trace: +explicit_file.cc:123: expected trace message +Stack trace: (omitted) + +[ FAILED ] ScopedTraceTest.WithExplicitFileAndLine +[----------] 1 test from NonFatalFailureInFixtureConstructorTest +[ RUN ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor +(expecting 5 failures) +googletest-output-test_.cc:#: Failure +Failed +Expected failure #1, in the test fixture c'tor. +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #2, in SetUp(). +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #3, in the test body. +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #4, in TearDown. +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #5, in the test fixture d'tor. +Stack trace: (omitted) + +[ FAILED ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor +[----------] 1 test from FatalFailureInFixtureConstructorTest +[ RUN ] FatalFailureInFixtureConstructorTest.FailureInConstructor +(expecting 2 failures) +googletest-output-test_.cc:#: Failure +Failed +Expected failure #1, in the test fixture c'tor. +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #2, in the test fixture d'tor. +Stack trace: (omitted) + +[ FAILED ] FatalFailureInFixtureConstructorTest.FailureInConstructor +[----------] 1 test from NonFatalFailureInSetUpTest +[ RUN ] NonFatalFailureInSetUpTest.FailureInSetUp +(expecting 4 failures) +googletest-output-test_.cc:#: Failure +Failed +Expected failure #1, in SetUp(). +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #2, in the test function. +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #3, in TearDown(). +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #4, in the test fixture d'tor. +Stack trace: (omitted) + +[ FAILED ] NonFatalFailureInSetUpTest.FailureInSetUp +[----------] 1 test from FatalFailureInSetUpTest +[ RUN ] FatalFailureInSetUpTest.FailureInSetUp +(expecting 3 failures) +googletest-output-test_.cc:#: Failure +Failed +Expected failure #1, in SetUp(). +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #2, in TearDown(). +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected failure #3, in the test fixture d'tor. +Stack trace: (omitted) + +[ FAILED ] FatalFailureInSetUpTest.FailureInSetUp +[----------] 1 test from AddFailureAtTest +[ RUN ] AddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber +foo.cc:42: Failure +Failed +Expected failure in foo.cc +Stack trace: (omitted) + +[ FAILED ] AddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber +[----------] 4 tests from MixedUpTestCaseTest +[ RUN ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo +[ OK ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo +[ RUN ] MixedUpTestCaseTest.SecondTestFromNamespaceFoo +[ OK ] MixedUpTestCaseTest.SecondTestFromNamespaceFoo +[ RUN ] MixedUpTestCaseTest.ThisShouldFail +gtest.cc:#: Failure +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. +Stack trace: (omitted) + +[ FAILED ] MixedUpTestCaseTest.ThisShouldFail +[ RUN ] MixedUpTestCaseTest.ThisShouldFailToo +gtest.cc:#: Failure +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. +Stack trace: (omitted) + +[ FAILED ] MixedUpTestCaseTest.ThisShouldFailToo +[----------] 2 tests from MixedUpTestCaseWithSameTestNameTest +[ RUN ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail +[ OK ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail +[ RUN ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail +gtest.cc:#: Failure +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. +Stack trace: (omitted) + +[ 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:#: Failure +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. +Stack trace: (omitted) + +[ 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:#: Failure +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. +Stack trace: (omitted) + +[ 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:#: Failure +Expected: 1 non-fatal failure + Actual: 0 failures +Stack trace: (omitted) + +[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure +[ RUN ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures +(expecting a failure) +gtest.cc:#: Failure +Expected: 1 non-fatal failure + Actual: 2 failures +googletest-output-test_.cc:#: Non-fatal failure: +Failed +Expected non-fatal failure 1. +Stack trace: (omitted) + + +googletest-output-test_.cc:#: Non-fatal failure: +Failed +Expected non-fatal failure 2. +Stack trace: (omitted) + + +Stack trace: (omitted) + +[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures +[ RUN ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure +(expecting a failure) +gtest.cc:#: Failure +Expected: 1 non-fatal failure + Actual: +googletest-output-test_.cc:#: Fatal failure: +Failed +Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) + +[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure +[ RUN ] ExpectNonfatalFailureTest.FailsWhenStatementReturns +(expecting a failure) +gtest.cc:#: Failure +Expected: 1 non-fatal failure + Actual: 0 failures +Stack trace: (omitted) + +[ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementReturns +[ RUN ] ExpectNonfatalFailureTest.FailsWhenStatementThrows +(expecting a failure) +gtest.cc:#: Failure +Expected: 1 non-fatal failure + Actual: 0 failures +Stack trace: (omitted) + +[ 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:#: Failure +Expected: 1 fatal failure + Actual: 0 failures +Stack trace: (omitted) + +[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure +[ RUN ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures +(expecting a failure) +gtest.cc:#: Failure +Expected: 1 fatal failure + Actual: 2 failures +googletest-output-test_.cc:#: Fatal failure: +Failed +Expected fatal failure. +Stack trace: (omitted) + + +googletest-output-test_.cc:#: Fatal failure: +Failed +Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) + +[ FAILED ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures +[ RUN ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure +(expecting a failure) +gtest.cc:#: Failure +Expected: 1 fatal failure + Actual: +googletest-output-test_.cc:#: Non-fatal failure: +Failed +Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) + +[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure +[ RUN ] ExpectFatalFailureTest.FailsWhenStatementReturns +(expecting a failure) +gtest.cc:#: Failure +Expected: 1 fatal failure + Actual: 0 failures +Stack trace: (omitted) + +[ FAILED ] ExpectFatalFailureTest.FailsWhenStatementReturns +[ RUN ] ExpectFatalFailureTest.FailsWhenStatementThrows +(expecting a failure) +gtest.cc:#: Failure +Expected: 1 fatal failure + Actual: 0 failures +Stack trace: (omitted) + +[ FAILED ] ExpectFatalFailureTest.FailsWhenStatementThrows +[----------] 2 tests from TypedTest/0, where TypeParam = int +[ RUN ] TypedTest/0.Success +[ OK ] TypedTest/0.Success +[ RUN ] TypedTest/0.Failure +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + TypeParam() + Which is: 0 +Expected failure +Stack trace: (omitted) + +[ 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 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1U + Which is: 1 + TypeParam() + Which is: '\0' +Expected failure +Stack trace: (omitted) + +[ 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 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1U + Which is: 1 + TypeParam() + Which is: 0 +Expected failure +Stack trace: (omitted) + +[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int +[----------] 4 tests from ExpectFailureTest +[ RUN ] ExpectFailureTest.ExpectFatalFailure +(expecting 1 failure) +gtest.cc:#: Failure +Expected: 1 fatal failure + Actual: +googletest-output-test_.cc:#: Success: +Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) + +(expecting 1 failure) +gtest.cc:#: Failure +Expected: 1 fatal failure + Actual: +googletest-output-test_.cc:#: Non-fatal failure: +Failed +Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) + +(expecting 1 failure) +gtest.cc:#: Failure +Expected: 1 fatal failure containing "Some other fatal failure expected." + Actual: +googletest-output-test_.cc:#: Fatal failure: +Failed +Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) + +[ FAILED ] ExpectFailureTest.ExpectFatalFailure +[ RUN ] ExpectFailureTest.ExpectNonFatalFailure +(expecting 1 failure) +gtest.cc:#: Failure +Expected: 1 non-fatal failure + Actual: +googletest-output-test_.cc:#: Success: +Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) + +(expecting 1 failure) +gtest.cc:#: Failure +Expected: 1 non-fatal failure + Actual: +googletest-output-test_.cc:#: Fatal failure: +Failed +Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) + +(expecting 1 failure) +gtest.cc:#: Failure +Expected: 1 non-fatal failure containing "Some other non-fatal failure." + Actual: +googletest-output-test_.cc:#: Non-fatal failure: +Failed +Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) + +[ FAILED ] ExpectFailureTest.ExpectNonFatalFailure +[ RUN ] ExpectFailureTest.ExpectFatalFailureOnAllThreads +(expecting 1 failure) +gtest.cc:#: Failure +Expected: 1 fatal failure + Actual: +googletest-output-test_.cc:#: Success: +Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) + +(expecting 1 failure) +gtest.cc:#: Failure +Expected: 1 fatal failure + Actual: +googletest-output-test_.cc:#: Non-fatal failure: +Failed +Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) + +(expecting 1 failure) +gtest.cc:#: Failure +Expected: 1 fatal failure containing "Some other fatal failure expected." + Actual: +googletest-output-test_.cc:#: Fatal failure: +Failed +Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) + +[ FAILED ] ExpectFailureTest.ExpectFatalFailureOnAllThreads +[ RUN ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads +(expecting 1 failure) +gtest.cc:#: Failure +Expected: 1 non-fatal failure + Actual: +googletest-output-test_.cc:#: Success: +Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) + +(expecting 1 failure) +gtest.cc:#: Failure +Expected: 1 non-fatal failure + Actual: +googletest-output-test_.cc:#: Fatal failure: +Failed +Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) + +(expecting 1 failure) +gtest.cc:#: Failure +Expected: 1 non-fatal failure containing "Some other non-fatal failure." + Actual: +googletest-output-test_.cc:#: Non-fatal failure: +Failed +Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) + +[ FAILED ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads +[----------] 2 tests from ExpectFailureWithThreadsTest +[ RUN ] ExpectFailureWithThreadsTest.ExpectFatalFailure +(expecting 2 failures) +googletest-output-test_.cc:#: Failure +Failed +Expected fatal failure. +Stack trace: (omitted) + +gtest.cc:#: Failure +Expected: 1 fatal failure + Actual: 0 failures +Stack trace: (omitted) + +[ FAILED ] ExpectFailureWithThreadsTest.ExpectFatalFailure +[ RUN ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure +(expecting 2 failures) +googletest-output-test_.cc:#: Failure +Failed +Expected non-fatal failure. +Stack trace: (omitted) + +gtest.cc:#: Failure +Expected: 1 non-fatal failure + Actual: 0 failures +Stack trace: (omitted) + +[ FAILED ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure +[----------] 1 test from ScopedFakeTestPartResultReporterTest +[ RUN ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread +(expecting 2 failures) +googletest-output-test_.cc:#: Failure +Failed +Expected fatal failure. +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Failed +Expected non-fatal failure. +Stack trace: (omitted) + +[ FAILED ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread +[----------] 1 test from PrintingFailingParams/FailingParamTest +[ RUN ] PrintingFailingParams/FailingParamTest.Fails/0 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + GetParam() + Which is: 2 +Stack trace: (omitted) + +[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 +[----------] 2 tests from PrintingStrings/ParamTest +[ RUN ] PrintingStrings/ParamTest.Success/a +[ OK ] PrintingStrings/ParamTest.Success/a +[ RUN ] PrintingStrings/ParamTest.Failure/a +googletest-output-test_.cc:#: Failure +Expected equality of these values: + "b" + GetParam() + Which is: "a" +Expected failure +Stack trace: (omitted) + +[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a" +[----------] Global test environment tear-down +BarEnvironment::TearDown() called. +googletest-output-test_.cc:#: Failure +Failed +Expected non-fatal failure. +Stack trace: (omitted) + +FooEnvironment::TearDown() called. +googletest-output-test_.cc:#: Failure +Failed +Expected fatal failure. +Stack trace: (omitted) + +[==========] 68 tests from 30 test cases ran. +[ PASSED ] 22 tests. +[ FAILED ] 46 tests, listed below: +[ FAILED ] NonfatalFailureTest.EscapesStringOperands +[ FAILED ] NonfatalFailureTest.DiffForLongStrings +[ FAILED ] FatalFailureTest.FatalFailureInSubroutine +[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine +[ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine +[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions +[ FAILED ] SCOPED_TRACETest.AcceptedValues +[ FAILED ] SCOPED_TRACETest.ObeysScopes +[ FAILED ] SCOPED_TRACETest.WorksInLoop +[ FAILED ] SCOPED_TRACETest.WorksInSubroutine +[ FAILED ] SCOPED_TRACETest.CanBeNested +[ FAILED ] SCOPED_TRACETest.CanBeRepeated +[ FAILED ] SCOPED_TRACETest.WorksConcurrently +[ FAILED ] ScopedTraceTest.WithExplicitFileAndLine +[ FAILED ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor +[ FAILED ] FatalFailureInFixtureConstructorTest.FailureInConstructor +[ FAILED ] NonFatalFailureInSetUpTest.FailureInSetUp +[ FAILED ] FatalFailureInSetUpTest.FailureInSetUp +[ FAILED ] AddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber +[ 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 ] ExpectFailureWithThreadsTest.ExpectFatalFailure +[ FAILED ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure +[ FAILED ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread +[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 +[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a" + +46 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) +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + x + Which is: 2 +Stack trace: (omitted) + +[ FAILED ] FatalFailureTest.FatalFailureInSubroutine (? ms) +[ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine +(expecting a failure that x should be 1) +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + x + Which is: 2 +Stack trace: (omitted) + +[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine (? ms) +[ RUN ] FatalFailureTest.NonfatalFailureInSubroutine +(expecting a failure on false) +googletest-output-test_.cc:#: Failure +Value of: false + Actual: false +Expected: true +Stack trace: (omitted) + +[ 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 +googletest-output-test_.cc:#: Failure +Expected: (3) >= (a[i]), actual: 3 vs 9 +Stack trace: (omitted) + +i == 2 +i == 3 +googletest-output-test_.cc:#: Failure +Expected: (3) >= (a[i]), actual: 3 vs 6 +Stack trace: (omitted) + +[ 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 +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 2 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. diff --git a/googletest/test/googletest-output-test.py b/googletest/test/googletest-output-test.py new file mode 100755 index 0000000..c1c3652 --- /dev/null +++ b/googletest/test/googletest-output-test.py @@ -0,0 +1,350 @@ +#!/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. + +"""Tests the text output of Google C++ Testing and Mocking Framework. + + +SYNOPSIS + googletest_output_test.py --build_dir=BUILD/DIR --gengolden + # where BUILD/DIR contains the built googletest-output-test_ file. + googletest_output_test.py --gengolden + googletest_output_test.py +""" + +__author__ = 'wan@google.com (Zhanyong Wan)' + +import difflib +import os +import re +import sys +import gtest_test_utils + + +# The flag for generating the golden file +GENGOLDEN_FLAG = '--gengolden' +CATCH_EXCEPTIONS_ENV_VAR_NAME = 'GTEST_CATCH_EXCEPTIONS' + +# The flag indicating stacktraces are not supported +NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' + +IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' +IS_WINDOWS = os.name == 'nt' + +# TODO(vladl@google.com): remove the _lin suffix. +GOLDEN_NAME = 'googletest-output-test-golden-lin.txt' + +PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('googletest-output-test_') + +# At least one command we exercise must not have the +# 'internal_skip_environment_and_ad_hoc_tests' argument. +COMMAND_LIST_TESTS = ({}, [PROGRAM_PATH, '--gtest_list_tests']) +COMMAND_WITH_COLOR = ({}, [PROGRAM_PATH, '--gtest_color=yes']) +COMMAND_WITH_TIME = ({}, [PROGRAM_PATH, + '--gtest_print_time', + 'internal_skip_environment_and_ad_hoc_tests', + '--gtest_filter=FatalFailureTest.*:LoggingTest.*']) +COMMAND_WITH_DISABLED = ( + {}, [PROGRAM_PATH, + '--gtest_also_run_disabled_tests', + 'internal_skip_environment_and_ad_hoc_tests', + '--gtest_filter=*DISABLED_*']) +COMMAND_WITH_SHARDING = ( + {'GTEST_SHARD_INDEX': '1', 'GTEST_TOTAL_SHARDS': '2'}, + [PROGRAM_PATH, + 'internal_skip_environment_and_ad_hoc_tests', + '--gtest_filter=PassingTest.*']) + +GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME) + + +def ToUnixLineEnding(s): + """Changes all Windows/Mac line endings in s to UNIX line endings.""" + + return s.replace('\r\n', '\n').replace('\r', '\n') + + +def RemoveLocations(test_output): + """Removes all file location info from a Google Test program's output. + + Args: + test_output: the output of a Google Test program. + + Returns: + output with all file location info (in the form of + 'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or + 'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by + 'FILE_NAME:#: '. + """ + + return re.sub(r'.*[/\\]((googletest-output-test_|gtest).cc)(\:\d+|\(\d+\))\: ', + r'\1:#: ', test_output) + + +def RemoveStackTraceDetails(output): + """Removes all stack traces from a Google Test program's output.""" + + # *? means "find the shortest string that matches". + return re.sub(r'Stack trace:(.|\n)*?\n\n', + 'Stack trace: (omitted)\n\n', output) + + +def RemoveStackTraces(output): + """Removes all traces of stack traces from a Google Test program's output.""" + + # *? means "find the shortest string that matches". + return re.sub(r'Stack trace:(.|\n)*?\n\n', '', output) + + +def RemoveTime(output): + """Removes all time information from a Google Test program's output.""" + + return re.sub(r'\(\d+ ms', '(? ms', output) + + +def RemoveTypeInfoDetails(test_output): + """Removes compiler-specific type info from Google Test program's output. + + Args: + test_output: the output of a Google Test program. + + Returns: + output with type information normalized to canonical form. + """ + + # some compilers output the name of type 'unsigned int' as 'unsigned' + 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.""" + + output = re.sub(r'\d+ tests?, listed below', + '? tests, listed below', output) + output = re.sub(r'\d+ FAILED TESTS', + '? FAILED TESTS', output) + output = re.sub(r'\d+ tests? from \d+ test cases?', + '? tests from ? test cases', output) + output = re.sub(r'\d+ tests? from ([a-zA-Z_])', + r'? tests from \1', output) + return re.sub(r'\d+ tests?\.', '? tests.', output) + + +def RemoveMatchingTests(test_output, pattern): + """Removes output of specified tests from a Google Test program's output. + + This function strips not only the beginning and the end of a test but also + all output in between. + + Args: + test_output: A string containing the test output. + pattern: A regex string that matches names of test cases or + tests to remove. + + Returns: + Contents of test_output with tests whose names match pattern removed. + """ + + test_output = re.sub( + r'.*\[ RUN \] .*%s(.|\n)*?\[( FAILED | OK )\] .*%s.*\n' % ( + pattern, pattern), + '', + test_output) + return re.sub(r'.*%s.*\n' % pattern, '', test_output) + + +def NormalizeOutput(output): + """Normalizes output (the output of googletest-output-test_.exe).""" + + output = ToUnixLineEnding(output) + output = RemoveLocations(output) + output = RemoveStackTraceDetails(output) + output = RemoveTime(output) + return output + + +def GetShellCommandOutput(env_cmd): + """Runs a command in a sub-process, and returns its output in a string. + + Args: + env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra + environment variables to set, and element 1 is a string with + the command and any flags. + + Returns: + A string with the command's combined standard and diagnostic output. + """ + + # Spawns cmd in a sub-process, and gets its standard I/O file objects. + # Set and save the environment properly. + environ = os.environ.copy() + environ.update(env_cmd[0]) + p = gtest_test_utils.Subprocess(env_cmd[1], env=environ) + + return p.output + + +def GetCommandOutput(env_cmd): + """Runs a command and returns its output with all file location + info stripped off. + + Args: + env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra + environment variables to set, and element 1 is a string with + the command and any flags. + """ + + # Disables exception pop-ups on Windows. + environ, cmdline = env_cmd + environ = dict(environ) # Ensures we are modifying a copy. + environ[CATCH_EXCEPTIONS_ENV_VAR_NAME] = '1' + return NormalizeOutput(GetShellCommandOutput((environ, cmdline))) + + +def GetOutputOfAllCommands(): + """Returns concatenated output from several representative commands.""" + + return (GetCommandOutput(COMMAND_WITH_COLOR) + + GetCommandOutput(COMMAND_WITH_TIME) + + GetCommandOutput(COMMAND_WITH_DISABLED) + + GetCommandOutput(COMMAND_WITH_SHARDING)) + + +test_list = GetShellCommandOutput(COMMAND_LIST_TESTS) +SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list +SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list +SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list +SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv + +CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and + SUPPORTS_TYPED_TESTS and + SUPPORTS_THREADS and + SUPPORTS_STACK_TRACES) + +class GTestOutputTest(gtest_test_utils.TestCase): + def RemoveUnsupportedTests(self, test_output): + if not SUPPORTS_DEATH_TESTS: + test_output = RemoveMatchingTests(test_output, 'DeathTest') + if not SUPPORTS_TYPED_TESTS: + test_output = RemoveMatchingTests(test_output, 'TypedTest') + test_output = RemoveMatchingTests(test_output, 'TypedDeathTest') + test_output = RemoveMatchingTests(test_output, 'TypeParamDeathTest') + if not SUPPORTS_THREADS: + test_output = RemoveMatchingTests(test_output, + 'ExpectFailureWithThreadsTest') + test_output = RemoveMatchingTests(test_output, + 'ScopedFakeTestPartResultReporterTest') + test_output = RemoveMatchingTests(test_output, + 'WorksConcurrently') + if not SUPPORTS_STACK_TRACES: + test_output = RemoveStackTraces(test_output) + + return test_output + + def testOutput(self): + output = GetOutputOfAllCommands() + + golden_file = open(GOLDEN_PATH, 'rb') + # A mis-configured source control system can cause \r appear in EOL + # sequences when we read the golden file irrespective of an operating + # system used. Therefore, we need to strip those \r's from newlines + # unconditionally. + golden = ToUnixLineEnding(golden_file.read()) + golden_file.close() + + # We want the test to pass regardless of certain features being + # supported or not. + + # We still have to remove type name specifics in all cases. + normalized_actual = RemoveTypeInfoDetails(output) + normalized_golden = RemoveTypeInfoDetails(golden) + + if CAN_GENERATE_GOLDEN_FILE: + self.assertEqual(normalized_golden, normalized_actual, + '\n'.join(difflib.unified_diff( + normalized_golden.split('\n'), + normalized_actual.split('\n'), + 'golden', 'actual'))) + else: + 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'): + open(os.path.join( + gtest_test_utils.GetSourceDir(), + '_googletest-output-test_normalized_actual.txt'), 'wb').write( + normalized_actual) + open(os.path.join( + gtest_test_utils.GetSourceDir(), + '_googletest-output-test_normalized_golden.txt'), 'wb').write( + normalized_golden) + + self.assertEqual(normalized_golden, normalized_actual) + + +if __name__ == '__main__': + if NO_STACKTRACE_SUPPORT_FLAG in sys.argv: + # unittest.main() can't handle unknown flags + sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG) + + if GENGOLDEN_FLAG in sys.argv: + if CAN_GENERATE_GOLDEN_FILE: + output = GetOutputOfAllCommands() + golden_file = open(GOLDEN_PATH, 'wb') + golden_file.write(output) + golden_file.close() + else: + message = ( + """Unable to write a golden file when compiled in an environment +that does not support all the required features (death tests, +typed tests, stack traces, and multiple threads). +Please build this test and generate the golden file using Blaze on Linux.""") + + sys.stderr.write(message) + sys.exit(1) + else: + gtest_test_utils.Main() diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc new file mode 100644 index 0000000..9ae9dc6 --- /dev/null +++ b/googletest/test/googletest-output-test_.cc @@ -0,0 +1,1067 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// The purpose of this file is to generate Google Test output under +// various conditions. The output will then be verified by +// gtest_output_test.py to ensure that Google Test generates the +// desired messages. Therefore, most tests in this file are MEANT TO +// FAIL. +// +// Author: wan@google.com (Zhanyong Wan) + +#include "gtest/gtest-spi.h" +#include "gtest/gtest.h" +#include "src/gtest-internal-inl.h" + +#include + +#if GTEST_IS_THREADSAFE +using testing::ScopedFakeTestPartResultReporter; +using testing::TestPartResultArray; + +using testing::internal::Notification; +using testing::internal::ThreadWithParam; +#endif + +namespace posix = ::testing::internal::posix; + +// Tests catching fatal failures. + +// A subroutine used by the following test. +void TestEq1(int x) { + ASSERT_EQ(1, x); +} + +// This function calls a test subroutine, catches the fatal failure it +// generates, and then returns early. +void TryTestSubroutine() { + // Calls a subrountine that yields a fatal failure. + TestEq1(2); + + // Catches the fatal failure and aborts the test. + // + // The testing::Test:: prefix is necessary when calling + // HasFatalFailure() outside of a TEST, TEST_F, or test fixture. + if (testing::Test::HasFatalFailure()) return; + + // If we get here, something is wrong. + FAIL() << "This should never be reached."; +} + +TEST(PassingTest, PassingTest1) { +} + +TEST(PassingTest, PassingTest2) { +} + +// Tests that parameters of failing parameterized tests are printed in the +// failing test summary. +class FailingParamTest : public testing::TestWithParam {}; + +TEST_P(FailingParamTest, Fails) { + EXPECT_EQ(1, GetParam()); +} + +// This generates a test which will fail. Google Test is expected to print +// its parameter when it outputs the list of all failed tests. +INSTANTIATE_TEST_CASE_P(PrintingFailingParams, + FailingParamTest, + testing::Values(2)); + +static const char kGoldenString[] = "\"Line\0 1\"\nLine 2"; + +TEST(NonfatalFailureTest, EscapesStringOperands) { + std::string actual = "actual \"string\""; + EXPECT_EQ(kGoldenString, actual); + + const char* golden = kGoldenString; + EXPECT_EQ(golden, actual); +} + +TEST(NonfatalFailureTest, DiffForLongStrings) { + std::string golden_str(kGoldenString, sizeof(kGoldenString) - 1); + EXPECT_EQ(golden_str, "Line 2"); +} + +// Tests catching a fatal failure in a subroutine. +TEST(FatalFailureTest, FatalFailureInSubroutine) { + printf("(expecting a failure that x should be 1)\n"); + + TryTestSubroutine(); +} + +// Tests catching a fatal failure in a nested subroutine. +TEST(FatalFailureTest, FatalFailureInNestedSubroutine) { + printf("(expecting a failure that x should be 1)\n"); + + // Calls a subrountine that yields a fatal failure. + TryTestSubroutine(); + + // Catches the fatal failure and aborts the test. + // + // When calling HasFatalFailure() inside a TEST, TEST_F, or test + // fixture, the testing::Test:: prefix is not needed. + if (HasFatalFailure()) return; + + // If we get here, something is wrong. + FAIL() << "This should never be reached."; +} + +// Tests HasFatalFailure() after a failed EXPECT check. +TEST(FatalFailureTest, NonfatalFailureInSubroutine) { + printf("(expecting a failure on false)\n"); + EXPECT_TRUE(false); // Generates a nonfatal failure + ASSERT_FALSE(HasFatalFailure()); // This should succeed. +} + +// Tests interleaving user logging and Google Test assertions. +TEST(LoggingTest, InterleavingLoggingAndAssertions) { + static const int a[4] = { + 3, 9, 2, 6 + }; + + printf("(expecting 2 failures on (3) >= (a[i]))\n"); + for (int i = 0; i < static_cast(sizeof(a)/sizeof(*a)); i++) { + printf("i == %d\n", i); + EXPECT_GE(3, a[i]); + } +} + +// Tests the SCOPED_TRACE macro. + +// A helper function for testing SCOPED_TRACE. +void SubWithoutTrace(int n) { + EXPECT_EQ(1, n); + ASSERT_EQ(2, n); +} + +// Another helper function for testing SCOPED_TRACE. +void SubWithTrace(int n) { + SCOPED_TRACE(testing::Message() << "n = " << n); + + SubWithoutTrace(n); +} + +TEST(SCOPED_TRACETest, AcceptedValues) { + SCOPED_TRACE("literal string"); + SCOPED_TRACE(std::string("std::string")); + SCOPED_TRACE(1337); // streamable type + const char* null_value = NULL; + SCOPED_TRACE(null_value); + + ADD_FAILURE() << "Just checking that all these values work fine."; +} + +// Tests that SCOPED_TRACE() obeys lexical scopes. +TEST(SCOPED_TRACETest, ObeysScopes) { + printf("(expected to fail)\n"); + + // There should be no trace before SCOPED_TRACE() is invoked. + ADD_FAILURE() << "This failure is expected, and shouldn't have a trace."; + + { + SCOPED_TRACE("Expected trace"); + // After SCOPED_TRACE(), a failure in the current scope should contain + // the trace. + ADD_FAILURE() << "This failure is expected, and should have a trace."; + } + + // Once the control leaves the scope of the SCOPED_TRACE(), there + // should be no trace again. + ADD_FAILURE() << "This failure is expected, and shouldn't have a trace."; +} + +// Tests that SCOPED_TRACE works inside a loop. +TEST(SCOPED_TRACETest, WorksInLoop) { + printf("(expected to fail)\n"); + + for (int i = 1; i <= 2; i++) { + SCOPED_TRACE(testing::Message() << "i = " << i); + + SubWithoutTrace(i); + } +} + +// Tests that SCOPED_TRACE works in a subroutine. +TEST(SCOPED_TRACETest, WorksInSubroutine) { + printf("(expected to fail)\n"); + + SubWithTrace(1); + SubWithTrace(2); +} + +// Tests that SCOPED_TRACE can be nested. +TEST(SCOPED_TRACETest, CanBeNested) { + printf("(expected to fail)\n"); + + SCOPED_TRACE(""); // A trace without a message. + + SubWithTrace(2); +} + +// Tests that multiple SCOPED_TRACEs can be used in the same scope. +TEST(SCOPED_TRACETest, CanBeRepeated) { + printf("(expected to fail)\n"); + + SCOPED_TRACE("A"); + ADD_FAILURE() + << "This failure is expected, and should contain trace point A."; + + SCOPED_TRACE("B"); + ADD_FAILURE() + << "This failure is expected, and should contain trace point A and B."; + + { + SCOPED_TRACE("C"); + ADD_FAILURE() << "This failure is expected, and should " + << "contain trace point A, B, and C."; + } + + SCOPED_TRACE("D"); + ADD_FAILURE() << "This failure is expected, and should " + << "contain trace point A, B, and D."; +} + +#if GTEST_IS_THREADSAFE +// Tests that SCOPED_TRACE()s can be used concurrently from multiple +// threads. Namely, an assertion should be affected by +// SCOPED_TRACE()s in its own thread only. + +// Here's the sequence of actions that happen in the test: +// +// Thread A (main) | Thread B (spawned) +// ===============================|================================ +// spawns thread B | +// -------------------------------+-------------------------------- +// waits for n1 | SCOPED_TRACE("Trace B"); +// | generates failure #1 +// | notifies n1 +// -------------------------------+-------------------------------- +// SCOPED_TRACE("Trace A"); | waits for n2 +// generates failure #2 | +// notifies n2 | +// -------------------------------|-------------------------------- +// waits for n3 | generates failure #3 +// | trace B dies +// | generates failure #4 +// | notifies n3 +// -------------------------------|-------------------------------- +// generates failure #5 | finishes +// trace A dies | +// generates failure #6 | +// -------------------------------|-------------------------------- +// waits for thread B to finish | + +struct CheckPoints { + Notification n1; + Notification n2; + Notification n3; +}; + +static void ThreadWithScopedTrace(CheckPoints* check_points) { + { + SCOPED_TRACE("Trace B"); + ADD_FAILURE() + << "Expected failure #1 (in thread B, only trace B alive)."; + check_points->n1.Notify(); + check_points->n2.WaitForNotification(); + + ADD_FAILURE() + << "Expected failure #3 (in thread B, trace A & B both alive)."; + } // Trace B dies here. + ADD_FAILURE() + << "Expected failure #4 (in thread B, only trace A alive)."; + check_points->n3.Notify(); +} + +TEST(SCOPED_TRACETest, WorksConcurrently) { + printf("(expecting 6 failures)\n"); + + CheckPoints check_points; + ThreadWithParam thread(&ThreadWithScopedTrace, + &check_points, + NULL); + check_points.n1.WaitForNotification(); + + { + SCOPED_TRACE("Trace A"); + ADD_FAILURE() + << "Expected failure #2 (in thread A, trace A & B both alive)."; + check_points.n2.Notify(); + check_points.n3.WaitForNotification(); + + ADD_FAILURE() + << "Expected failure #5 (in thread A, only trace A alive)."; + } // Trace A dies here. + ADD_FAILURE() + << "Expected failure #6 (in thread A, no trace alive)."; + thread.Join(); +} +#endif // GTEST_IS_THREADSAFE + +// Tests basic functionality of the ScopedTrace utility (most of its features +// are already tested in SCOPED_TRACETest). +TEST(ScopedTraceTest, WithExplicitFileAndLine) { + testing::ScopedTrace trace("explicit_file.cc", 123, "expected trace message"); + ADD_FAILURE() << "Check that the trace is attached to a particular location."; +} + +TEST(DisabledTestsWarningTest, + DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning) { + // This test body is intentionally empty. Its sole purpose is for + // verifying that the --gtest_also_run_disabled_tests flag + // suppresses the "YOU HAVE 12 DISABLED TESTS" warning at the end of + // the test output. +} + +// Tests using assertions outside of TEST and TEST_F. +// +// This function creates two failures intentionally. +void AdHocTest() { + printf("The non-test part of the code is expected to have 2 failures.\n\n"); + EXPECT_TRUE(false); + EXPECT_EQ(2, 3); +} + +// Runs all TESTs, all TEST_Fs, and the ad hoc test. +int RunAllTests() { + AdHocTest(); + return RUN_ALL_TESTS(); +} + +// Tests non-fatal failures in the fixture constructor. +class NonFatalFailureInFixtureConstructorTest : public testing::Test { + protected: + NonFatalFailureInFixtureConstructorTest() { + printf("(expecting 5 failures)\n"); + ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor."; + } + + ~NonFatalFailureInFixtureConstructorTest() { + ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor."; + } + + virtual void SetUp() { + ADD_FAILURE() << "Expected failure #2, in SetUp()."; + } + + virtual void TearDown() { + ADD_FAILURE() << "Expected failure #4, in TearDown."; + } +}; + +TEST_F(NonFatalFailureInFixtureConstructorTest, FailureInConstructor) { + ADD_FAILURE() << "Expected failure #3, in the test body."; +} + +// Tests fatal failures in the fixture constructor. +class FatalFailureInFixtureConstructorTest : public testing::Test { + protected: + FatalFailureInFixtureConstructorTest() { + printf("(expecting 2 failures)\n"); + Init(); + } + + ~FatalFailureInFixtureConstructorTest() { + ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor."; + } + + virtual void SetUp() { + ADD_FAILURE() << "UNEXPECTED failure in SetUp(). " + << "We should never get here, as the test fixture c'tor " + << "had a fatal failure."; + } + + virtual void TearDown() { + ADD_FAILURE() << "UNEXPECTED failure in TearDown(). " + << "We should never get here, as the test fixture c'tor " + << "had a fatal failure."; + } + + private: + void Init() { + FAIL() << "Expected failure #1, in the test fixture c'tor."; + } +}; + +TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) { + ADD_FAILURE() << "UNEXPECTED failure in the test body. " + << "We should never get here, as the test fixture c'tor " + << "had a fatal failure."; +} + +// Tests non-fatal failures in SetUp(). +class NonFatalFailureInSetUpTest : public testing::Test { + protected: + virtual ~NonFatalFailureInSetUpTest() { + Deinit(); + } + + virtual void SetUp() { + printf("(expecting 4 failures)\n"); + ADD_FAILURE() << "Expected failure #1, in SetUp()."; + } + + virtual void TearDown() { + FAIL() << "Expected failure #3, in TearDown()."; + } + private: + void Deinit() { + FAIL() << "Expected failure #4, in the test fixture d'tor."; + } +}; + +TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) { + FAIL() << "Expected failure #2, in the test function."; +} + +// Tests fatal failures in SetUp(). +class FatalFailureInSetUpTest : public testing::Test { + protected: + virtual ~FatalFailureInSetUpTest() { + Deinit(); + } + + virtual void SetUp() { + printf("(expecting 3 failures)\n"); + FAIL() << "Expected failure #1, in SetUp()."; + } + + virtual void TearDown() { + FAIL() << "Expected failure #2, in TearDown()."; + } + private: + void Deinit() { + FAIL() << "Expected failure #3, in the test fixture d'tor."; + } +}; + +TEST_F(FatalFailureInSetUpTest, FailureInSetUp) { + FAIL() << "UNEXPECTED failure in the test function. " + << "We should never get here, as SetUp() failed."; +} + +TEST(AddFailureAtTest, MessageContainsSpecifiedFileAndLineNumber) { + ADD_FAILURE_AT("foo.cc", 42) << "Expected failure in foo.cc"; +} + +#if GTEST_IS_THREADSAFE + +// A unary function that may die. +void DieIf(bool should_die) { + GTEST_CHECK_(!should_die) << " - death inside DieIf()."; +} + +// Tests running death tests in a multi-threaded context. + +// Used for coordination between the main and the spawn thread. +struct SpawnThreadNotifications { + SpawnThreadNotifications() {} + + Notification spawn_thread_started; + Notification spawn_thread_ok_to_terminate; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(SpawnThreadNotifications); +}; + +// The function to be executed in the thread spawn by the +// MultipleThreads test (below). +static void ThreadRoutine(SpawnThreadNotifications* notifications) { + // Signals the main thread that this thread has started. + notifications->spawn_thread_started.Notify(); + + // Waits for permission to finish from the main thread. + notifications->spawn_thread_ok_to_terminate.WaitForNotification(); +} + +// This is a death-test test, but it's not named with a DeathTest +// suffix. It starts threads which might interfere with later +// death tests, so it must run after all other death tests. +class DeathTestAndMultiThreadsTest : public testing::Test { + protected: + // Starts a thread and waits for it to begin. + virtual void SetUp() { + thread_.reset(new ThreadWithParam( + &ThreadRoutine, ¬ifications_, NULL)); + notifications_.spawn_thread_started.WaitForNotification(); + } + // Tells the thread to finish, and reaps it. + // Depending on the version of the thread library in use, + // a manager thread might still be left running that will interfere + // with later death tests. This is unfortunate, but this class + // cleans up after itself as best it can. + virtual void TearDown() { + notifications_.spawn_thread_ok_to_terminate.Notify(); + } + + private: + SpawnThreadNotifications notifications_; + testing::internal::scoped_ptr > + thread_; +}; + +#endif // GTEST_IS_THREADSAFE + +// The MixedUpTestCaseTest test case verifies that Google Test will fail a +// test if it uses a different fixture class than what other tests in +// the same test case use. It deliberately contains two fixture +// classes with the same name but defined in different namespaces. + +// The MixedUpTestCaseWithSameTestNameTest test case verifies that +// when the user defines two tests with the same test case name AND +// same test name (but in different namespaces), the second test will +// fail. + +namespace foo { + +class MixedUpTestCaseTest : public testing::Test { +}; + +TEST_F(MixedUpTestCaseTest, FirstTestFromNamespaceFoo) {} +TEST_F(MixedUpTestCaseTest, SecondTestFromNamespaceFoo) {} + +class MixedUpTestCaseWithSameTestNameTest : public testing::Test { +}; + +TEST_F(MixedUpTestCaseWithSameTestNameTest, + TheSecondTestWithThisNameShouldFail) {} + +} // namespace foo + +namespace bar { + +class MixedUpTestCaseTest : public testing::Test { +}; + +// The following two tests are expected to fail. We rely on the +// golden file to check that Google Test generates the right error message. +TEST_F(MixedUpTestCaseTest, ThisShouldFail) {} +TEST_F(MixedUpTestCaseTest, ThisShouldFailToo) {} + +class MixedUpTestCaseWithSameTestNameTest : public testing::Test { +}; + +// Expected to fail. We rely on the golden file to check that Google Test +// generates the right error message. +TEST_F(MixedUpTestCaseWithSameTestNameTest, + TheSecondTestWithThisNameShouldFail) {} + +} // namespace bar + +// The following two test cases verify that Google Test catches the user +// error of mixing TEST and TEST_F in the same test case. The first +// test case checks the scenario where TEST_F appears before TEST, and +// the second one checks where TEST appears before TEST_F. + +class TEST_F_before_TEST_in_same_test_case : public testing::Test { +}; + +TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {} + +// Expected to fail. We rely on the golden file to check that Google Test +// generates the right error message. +TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {} + +class TEST_before_TEST_F_in_same_test_case : public testing::Test { +}; + +TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {} + +// Expected to fail. We rely on the golden file to check that Google Test +// generates the right error message. +TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) { +} + +// Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE(). +int global_integer = 0; + +// Tests that EXPECT_NONFATAL_FAILURE() can reference global variables. +TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) { + global_integer = 0; + EXPECT_NONFATAL_FAILURE({ + EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; + }, "Expected non-fatal failure."); +} + +// Tests that EXPECT_NONFATAL_FAILURE() can reference local variables +// (static or not). +TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) { + int m = 0; + static int n; + n = 1; + EXPECT_NONFATAL_FAILURE({ + EXPECT_EQ(m, n) << "Expected non-fatal failure."; + }, "Expected non-fatal failure."); +} + +// Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly +// one non-fatal failure and no fatal failure. +TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) { + EXPECT_NONFATAL_FAILURE({ + ADD_FAILURE() << "Expected non-fatal failure."; + }, "Expected non-fatal failure."); +} + +// Tests that EXPECT_NONFATAL_FAILURE() fails when there is no +// non-fatal failure. +TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) { + printf("(expecting a failure)\n"); + EXPECT_NONFATAL_FAILURE({ + }, ""); +} + +// Tests that EXPECT_NONFATAL_FAILURE() fails when there are two +// non-fatal failures. +TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) { + printf("(expecting a failure)\n"); + EXPECT_NONFATAL_FAILURE({ + ADD_FAILURE() << "Expected non-fatal failure 1."; + ADD_FAILURE() << "Expected non-fatal failure 2."; + }, ""); +} + +// Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal +// failure. +TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) { + printf("(expecting a failure)\n"); + EXPECT_NONFATAL_FAILURE({ + FAIL() << "Expected fatal failure."; + }, ""); +} + +// Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being +// tested returns. +TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) { + printf("(expecting a failure)\n"); + EXPECT_NONFATAL_FAILURE({ + return; + }, ""); +} + +#if GTEST_HAS_EXCEPTIONS + +// Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being +// tested throws. +TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) { + printf("(expecting a failure)\n"); + try { + EXPECT_NONFATAL_FAILURE({ + throw 0; + }, ""); + } catch(int) { // NOLINT + } +} + +#endif // GTEST_HAS_EXCEPTIONS + +// Tests that EXPECT_FATAL_FAILURE() can reference global variables. +TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) { + global_integer = 0; + EXPECT_FATAL_FAILURE({ + ASSERT_EQ(1, global_integer) << "Expected fatal failure."; + }, "Expected fatal failure."); +} + +// Tests that EXPECT_FATAL_FAILURE() can reference local static +// variables. +TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) { + static int n; + n = 1; + EXPECT_FATAL_FAILURE({ + ASSERT_EQ(0, n) << "Expected fatal failure."; + }, "Expected fatal failure."); +} + +// Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly +// one fatal failure and no non-fatal failure. +TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) { + EXPECT_FATAL_FAILURE({ + FAIL() << "Expected fatal failure."; + }, "Expected fatal failure."); +} + +// Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal +// failure. +TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) { + printf("(expecting a failure)\n"); + EXPECT_FATAL_FAILURE({ + }, ""); +} + +// A helper for generating a fatal failure. +void FatalFailure() { + FAIL() << "Expected fatal failure."; +} + +// Tests that EXPECT_FATAL_FAILURE() fails when there are two +// fatal failures. +TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) { + printf("(expecting a failure)\n"); + EXPECT_FATAL_FAILURE({ + FatalFailure(); + FatalFailure(); + }, ""); +} + +// Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal +// failure. +TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) { + printf("(expecting a failure)\n"); + EXPECT_FATAL_FAILURE({ + ADD_FAILURE() << "Expected non-fatal failure."; + }, ""); +} + +// Tests that EXPECT_FATAL_FAILURE() fails when the statement being +// tested returns. +TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) { + printf("(expecting a failure)\n"); + EXPECT_FATAL_FAILURE({ + return; + }, ""); +} + +#if GTEST_HAS_EXCEPTIONS + +// Tests that EXPECT_FATAL_FAILURE() fails when the statement being +// tested throws. +TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) { + printf("(expecting a failure)\n"); + try { + EXPECT_FATAL_FAILURE({ + throw 0; + }, ""); + } catch(int) { // NOLINT + } +} + +#endif // GTEST_HAS_EXCEPTIONS + +// This #ifdef block tests the output of value-parameterized tests. + +std::string ParamNameFunc(const testing::TestParamInfo& info) { + return info.param; +} + +class ParamTest : public testing::TestWithParam { +}; + +TEST_P(ParamTest, Success) { + EXPECT_EQ("a", GetParam()); +} + +TEST_P(ParamTest, Failure) { + EXPECT_EQ("b", GetParam()) << "Expected failure"; +} + +INSTANTIATE_TEST_CASE_P(PrintingStrings, + ParamTest, + testing::Values(std::string("a")), + ParamNameFunc); + +// This #ifdef block tests the output of typed tests. +#if GTEST_HAS_TYPED_TEST + +template +class TypedTest : public testing::Test { +}; + +TYPED_TEST_CASE(TypedTest, testing::Types); + +TYPED_TEST(TypedTest, Success) { + EXPECT_EQ(0, TypeParam()); +} + +TYPED_TEST(TypedTest, Failure) { + EXPECT_EQ(1, TypeParam()) << "Expected failure"; +} + +#endif // GTEST_HAS_TYPED_TEST + +// This #ifdef block tests the output of type-parameterized tests. +#if GTEST_HAS_TYPED_TEST_P + +template +class TypedTestP : public testing::Test { +}; + +TYPED_TEST_CASE_P(TypedTestP); + +TYPED_TEST_P(TypedTestP, Success) { + EXPECT_EQ(0U, TypeParam()); +} + +TYPED_TEST_P(TypedTestP, Failure) { + EXPECT_EQ(1U, TypeParam()) << "Expected failure"; +} + +REGISTER_TYPED_TEST_CASE_P(TypedTestP, Success, Failure); + +typedef testing::Types UnsignedTypes; +INSTANTIATE_TYPED_TEST_CASE_P(Unsigned, TypedTestP, UnsignedTypes); + +#endif // GTEST_HAS_TYPED_TEST_P + +#if GTEST_HAS_DEATH_TEST + +// We rely on the golden file to verify that tests whose test case +// name ends with DeathTest are run first. + +TEST(ADeathTest, ShouldRunFirst) { +} + +# if GTEST_HAS_TYPED_TEST + +// We rely on the golden file to verify that typed tests whose test +// case name ends with DeathTest are run first. + +template +class ATypedDeathTest : public testing::Test { +}; + +typedef testing::Types NumericTypes; +TYPED_TEST_CASE(ATypedDeathTest, NumericTypes); + +TYPED_TEST(ATypedDeathTest, ShouldRunFirst) { +} + +# endif // GTEST_HAS_TYPED_TEST + +# if GTEST_HAS_TYPED_TEST_P + + +// We rely on the golden file to verify that type-parameterized tests +// whose test case name ends with DeathTest are run first. + +template +class ATypeParamDeathTest : public testing::Test { +}; + +TYPED_TEST_CASE_P(ATypeParamDeathTest); + +TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) { +} + +REGISTER_TYPED_TEST_CASE_P(ATypeParamDeathTest, ShouldRunFirst); + +INSTANTIATE_TYPED_TEST_CASE_P(My, ATypeParamDeathTest, NumericTypes); + +# endif // GTEST_HAS_TYPED_TEST_P + +#endif // GTEST_HAS_DEATH_TEST + +// Tests various failure conditions of +// EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}. +class ExpectFailureTest : public testing::Test { + public: // Must be public and not protected due to a bug in g++ 3.4.2. + enum FailureMode { + FATAL_FAILURE, + NONFATAL_FAILURE + }; + static void AddFailure(FailureMode failure) { + if (failure == FATAL_FAILURE) { + FAIL() << "Expected fatal failure."; + } else { + ADD_FAILURE() << "Expected non-fatal failure."; + } + } +}; + +TEST_F(ExpectFailureTest, ExpectFatalFailure) { + // Expected fatal failure, but succeeds. + printf("(expecting 1 failure)\n"); + EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure."); + // Expected fatal failure, but got a non-fatal failure. + printf("(expecting 1 failure)\n"); + EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal " + "failure."); + // Wrong message. + printf("(expecting 1 failure)\n"); + EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Some other fatal failure " + "expected."); +} + +TEST_F(ExpectFailureTest, ExpectNonFatalFailure) { + // Expected non-fatal failure, but succeeds. + printf("(expecting 1 failure)\n"); + EXPECT_NONFATAL_FAILURE(SUCCEED(), "Expected non-fatal failure."); + // Expected non-fatal failure, but got a fatal failure. + printf("(expecting 1 failure)\n"); + EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure."); + // Wrong message. + printf("(expecting 1 failure)\n"); + EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Some other non-fatal " + "failure."); +} + +#if GTEST_IS_THREADSAFE + +class ExpectFailureWithThreadsTest : public ExpectFailureTest { + protected: + static void AddFailureInOtherThread(FailureMode failure) { + ThreadWithParam thread(&AddFailure, failure, NULL); + thread.Join(); + } +}; + +TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailure) { + // We only intercept the current thread. + printf("(expecting 2 failures)\n"); + EXPECT_FATAL_FAILURE(AddFailureInOtherThread(FATAL_FAILURE), + "Expected fatal failure."); +} + +TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailure) { + // We only intercept the current thread. + printf("(expecting 2 failures)\n"); + EXPECT_NONFATAL_FAILURE(AddFailureInOtherThread(NONFATAL_FAILURE), + "Expected non-fatal failure."); +} + +typedef ExpectFailureWithThreadsTest ScopedFakeTestPartResultReporterTest; + +// Tests that the ScopedFakeTestPartResultReporter only catches failures from +// the current thread if it is instantiated with INTERCEPT_ONLY_CURRENT_THREAD. +TEST_F(ScopedFakeTestPartResultReporterTest, InterceptOnlyCurrentThread) { + printf("(expecting 2 failures)\n"); + TestPartResultArray results; + { + ScopedFakeTestPartResultReporter reporter( + ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD, + &results); + AddFailureInOtherThread(FATAL_FAILURE); + AddFailureInOtherThread(NONFATAL_FAILURE); + } + // The two failures should not have been intercepted. + EXPECT_EQ(0, results.size()) << "This shouldn't fail."; +} + +#endif // GTEST_IS_THREADSAFE + +TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) { + // Expected fatal failure, but succeeds. + printf("(expecting 1 failure)\n"); + EXPECT_FATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected fatal failure."); + // Expected fatal failure, but got a non-fatal failure. + printf("(expecting 1 failure)\n"); + EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE), + "Expected non-fatal failure."); + // Wrong message. + printf("(expecting 1 failure)\n"); + EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE), + "Some other fatal failure expected."); +} + +TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) { + // Expected non-fatal failure, but succeeds. + printf("(expecting 1 failure)\n"); + EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal " + "failure."); + // Expected non-fatal failure, but got a fatal failure. + printf("(expecting 1 failure)\n"); + EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE), + "Expected fatal failure."); + // Wrong message. + printf("(expecting 1 failure)\n"); + EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE), + "Some other non-fatal failure."); +} + + +// Two test environments for testing testing::AddGlobalTestEnvironment(). + +class FooEnvironment : public testing::Environment { + public: + virtual void SetUp() { + printf("%s", "FooEnvironment::SetUp() called.\n"); + } + + virtual void TearDown() { + printf("%s", "FooEnvironment::TearDown() called.\n"); + FAIL() << "Expected fatal failure."; + } +}; + +class BarEnvironment : public testing::Environment { + public: + virtual void SetUp() { + printf("%s", "BarEnvironment::SetUp() called.\n"); + } + + virtual void TearDown() { + printf("%s", "BarEnvironment::TearDown() called.\n"); + ADD_FAILURE() << "Expected non-fatal failure."; + } +}; + +// The main function. +// +// The idea is to use Google Test to run all the tests we have defined (some +// of them are intended to fail), and then compare the test results +// with the "golden" file. +int main(int argc, char **argv) { + testing::GTEST_FLAG(print_time) = false; + + // We just run the tests, knowing some of them are intended to fail. + // We will use a separate Python script to compare the output of + // this program with the golden file. + + // It's hard to test InitGoogleTest() directly, as it has many + // global side effects. The following line serves as a sanity test + // for it. + testing::InitGoogleTest(&argc, argv); + bool internal_skip_environment_and_ad_hoc_tests = + std::count(argv, argv + argc, + std::string("internal_skip_environment_and_ad_hoc_tests")) > 0; + +#if GTEST_HAS_DEATH_TEST + if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") { + // Skip the usual output capturing if we're running as the child + // process of an threadsafe-style death test. +# if GTEST_OS_WINDOWS + posix::FReopen("nul:", "w", stdout); +# else + posix::FReopen("/dev/null", "w", stdout); +# endif // GTEST_OS_WINDOWS + return RUN_ALL_TESTS(); + } +#endif // GTEST_HAS_DEATH_TEST + + if (internal_skip_environment_and_ad_hoc_tests) + return RUN_ALL_TESTS(); + + // Registers two global test environments. + // The golden file verifies that they are set up in the order they + // are registered, and torn down in the reverse order. + testing::AddGlobalTestEnvironment(new FooEnvironment); + testing::AddGlobalTestEnvironment(new BarEnvironment); + + return RunAllTests(); +} diff --git a/googletest/test/gtest_output_test.py b/googletest/test/gtest_output_test.py deleted file mode 100755 index 63763b9..0000000 --- a/googletest/test/gtest_output_test.py +++ /dev/null @@ -1,350 +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. - -"""Tests the text output of Google C++ Testing and Mocking Framework. - - -SYNOPSIS - gtest_output_test.py --build_dir=BUILD/DIR --gengolden - # where BUILD/DIR contains the built gtest_output_test_ file. - gtest_output_test.py --gengolden - gtest_output_test.py -""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import difflib -import os -import re -import sys -import gtest_test_utils - - -# The flag for generating the golden file -GENGOLDEN_FLAG = '--gengolden' -CATCH_EXCEPTIONS_ENV_VAR_NAME = 'GTEST_CATCH_EXCEPTIONS' - -# The flag indicating stacktraces are not supported -NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' - -IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' -IS_WINDOWS = os.name == 'nt' - -# 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_') - -# At least one command we exercise must not have the -# 'internal_skip_environment_and_ad_hoc_tests' argument. -COMMAND_LIST_TESTS = ({}, [PROGRAM_PATH, '--gtest_list_tests']) -COMMAND_WITH_COLOR = ({}, [PROGRAM_PATH, '--gtest_color=yes']) -COMMAND_WITH_TIME = ({}, [PROGRAM_PATH, - '--gtest_print_time', - 'internal_skip_environment_and_ad_hoc_tests', - '--gtest_filter=FatalFailureTest.*:LoggingTest.*']) -COMMAND_WITH_DISABLED = ( - {}, [PROGRAM_PATH, - '--gtest_also_run_disabled_tests', - 'internal_skip_environment_and_ad_hoc_tests', - '--gtest_filter=*DISABLED_*']) -COMMAND_WITH_SHARDING = ( - {'GTEST_SHARD_INDEX': '1', 'GTEST_TOTAL_SHARDS': '2'}, - [PROGRAM_PATH, - 'internal_skip_environment_and_ad_hoc_tests', - '--gtest_filter=PassingTest.*']) - -GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME) - - -def ToUnixLineEnding(s): - """Changes all Windows/Mac line endings in s to UNIX line endings.""" - - return s.replace('\r\n', '\n').replace('\r', '\n') - - -def RemoveLocations(test_output): - """Removes all file location info from a Google Test program's output. - - Args: - test_output: the output of a Google Test program. - - Returns: - output with all file location info (in the form of - 'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or - 'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by - 'FILE_NAME:#: '. - """ - - return re.sub(r'.*[/\\]((gtest_output_test_|gtest).cc)(\:\d+|\(\d+\))\: ', - r'\1:#: ', test_output) - - -def RemoveStackTraceDetails(output): - """Removes all stack traces from a Google Test program's output.""" - - # *? means "find the shortest string that matches". - return re.sub(r'Stack trace:(.|\n)*?\n\n', - 'Stack trace: (omitted)\n\n', output) - - -def RemoveStackTraces(output): - """Removes all traces of stack traces from a Google Test program's output.""" - - # *? means "find the shortest string that matches". - return re.sub(r'Stack trace:(.|\n)*?\n\n', '', output) - - -def RemoveTime(output): - """Removes all time information from a Google Test program's output.""" - - return re.sub(r'\(\d+ ms', '(? ms', output) - - -def RemoveTypeInfoDetails(test_output): - """Removes compiler-specific type info from Google Test program's output. - - Args: - test_output: the output of a Google Test program. - - Returns: - output with type information normalized to canonical form. - """ - - # some compilers output the name of type 'unsigned int' as 'unsigned' - 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.""" - - output = re.sub(r'\d+ tests?, listed below', - '? tests, listed below', output) - output = re.sub(r'\d+ FAILED TESTS', - '? FAILED TESTS', output) - output = re.sub(r'\d+ tests? from \d+ test cases?', - '? tests from ? test cases', output) - output = re.sub(r'\d+ tests? from ([a-zA-Z_])', - r'? tests from \1', output) - return re.sub(r'\d+ tests?\.', '? tests.', output) - - -def RemoveMatchingTests(test_output, pattern): - """Removes output of specified tests from a Google Test program's output. - - This function strips not only the beginning and the end of a test but also - all output in between. - - Args: - test_output: A string containing the test output. - pattern: A regex string that matches names of test cases or - tests to remove. - - Returns: - Contents of test_output with tests whose names match pattern removed. - """ - - test_output = re.sub( - r'.*\[ RUN \] .*%s(.|\n)*?\[( FAILED | OK )\] .*%s.*\n' % ( - pattern, pattern), - '', - test_output) - return re.sub(r'.*%s.*\n' % pattern, '', test_output) - - -def NormalizeOutput(output): - """Normalizes output (the output of gtest_output_test_.exe).""" - - output = ToUnixLineEnding(output) - output = RemoveLocations(output) - output = RemoveStackTraceDetails(output) - output = RemoveTime(output) - return output - - -def GetShellCommandOutput(env_cmd): - """Runs a command in a sub-process, and returns its output in a string. - - Args: - env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra - environment variables to set, and element 1 is a string with - the command and any flags. - - Returns: - A string with the command's combined standard and diagnostic output. - """ - - # Spawns cmd in a sub-process, and gets its standard I/O file objects. - # Set and save the environment properly. - environ = os.environ.copy() - environ.update(env_cmd[0]) - p = gtest_test_utils.Subprocess(env_cmd[1], env=environ) - - return p.output - - -def GetCommandOutput(env_cmd): - """Runs a command and returns its output with all file location - info stripped off. - - Args: - env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra - environment variables to set, and element 1 is a string with - the command and any flags. - """ - - # Disables exception pop-ups on Windows. - environ, cmdline = env_cmd - environ = dict(environ) # Ensures we are modifying a copy. - environ[CATCH_EXCEPTIONS_ENV_VAR_NAME] = '1' - return NormalizeOutput(GetShellCommandOutput((environ, cmdline))) - - -def GetOutputOfAllCommands(): - """Returns concatenated output from several representative commands.""" - - return (GetCommandOutput(COMMAND_WITH_COLOR) + - GetCommandOutput(COMMAND_WITH_TIME) + - GetCommandOutput(COMMAND_WITH_DISABLED) + - GetCommandOutput(COMMAND_WITH_SHARDING)) - - -test_list = GetShellCommandOutput(COMMAND_LIST_TESTS) -SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list -SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list -SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list -SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv - -CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and - SUPPORTS_TYPED_TESTS and - SUPPORTS_THREADS and - SUPPORTS_STACK_TRACES) - -class GTestOutputTest(gtest_test_utils.TestCase): - def RemoveUnsupportedTests(self, test_output): - if not SUPPORTS_DEATH_TESTS: - test_output = RemoveMatchingTests(test_output, 'DeathTest') - if not SUPPORTS_TYPED_TESTS: - test_output = RemoveMatchingTests(test_output, 'TypedTest') - test_output = RemoveMatchingTests(test_output, 'TypedDeathTest') - test_output = RemoveMatchingTests(test_output, 'TypeParamDeathTest') - if not SUPPORTS_THREADS: - test_output = RemoveMatchingTests(test_output, - 'ExpectFailureWithThreadsTest') - test_output = RemoveMatchingTests(test_output, - 'ScopedFakeTestPartResultReporterTest') - test_output = RemoveMatchingTests(test_output, - 'WorksConcurrently') - if not SUPPORTS_STACK_TRACES: - test_output = RemoveStackTraces(test_output) - - return test_output - - def testOutput(self): - output = GetOutputOfAllCommands() - - golden_file = open(GOLDEN_PATH, 'rb') - # A mis-configured source control system can cause \r appear in EOL - # sequences when we read the golden file irrespective of an operating - # system used. Therefore, we need to strip those \r's from newlines - # unconditionally. - golden = ToUnixLineEnding(golden_file.read()) - golden_file.close() - - # We want the test to pass regardless of certain features being - # supported or not. - - # We still have to remove type name specifics in all cases. - normalized_actual = RemoveTypeInfoDetails(output) - normalized_golden = RemoveTypeInfoDetails(golden) - - if CAN_GENERATE_GOLDEN_FILE: - self.assertEqual(normalized_golden, normalized_actual, - '\n'.join(difflib.unified_diff( - normalized_golden.split('\n'), - normalized_actual.split('\n'), - 'golden', 'actual'))) - else: - 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'): - open(os.path.join( - gtest_test_utils.GetSourceDir(), - '_gtest_output_test_normalized_actual.txt'), 'wb').write( - normalized_actual) - open(os.path.join( - gtest_test_utils.GetSourceDir(), - '_gtest_output_test_normalized_golden.txt'), 'wb').write( - normalized_golden) - - self.assertEqual(normalized_golden, normalized_actual) - - -if __name__ == '__main__': - if NO_STACKTRACE_SUPPORT_FLAG in sys.argv: - # unittest.main() can't handle unknown flags - sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG) - - if GENGOLDEN_FLAG in sys.argv: - if CAN_GENERATE_GOLDEN_FILE: - output = GetOutputOfAllCommands() - golden_file = open(GOLDEN_PATH, 'wb') - golden_file.write(output) - golden_file.close() - else: - message = ( - """Unable to write a golden file when compiled in an environment -that does not support all the required features (death tests, -typed tests, stack traces, and multiple threads). -Please build this test and generate the golden file using Blaze on Linux.""") - - sys.stderr.write(message) - sys.exit(1) - else: - gtest_test_utils.Main() diff --git a/googletest/test/gtest_output_test_.cc b/googletest/test/gtest_output_test_.cc deleted file mode 100644 index 9ae9dc6..0000000 --- a/googletest/test/gtest_output_test_.cc +++ /dev/null @@ -1,1067 +0,0 @@ -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// The purpose of this file is to generate Google Test output under -// various conditions. The output will then be verified by -// gtest_output_test.py to ensure that Google Test generates the -// desired messages. Therefore, most tests in this file are MEANT TO -// FAIL. -// -// Author: wan@google.com (Zhanyong Wan) - -#include "gtest/gtest-spi.h" -#include "gtest/gtest.h" -#include "src/gtest-internal-inl.h" - -#include - -#if GTEST_IS_THREADSAFE -using testing::ScopedFakeTestPartResultReporter; -using testing::TestPartResultArray; - -using testing::internal::Notification; -using testing::internal::ThreadWithParam; -#endif - -namespace posix = ::testing::internal::posix; - -// Tests catching fatal failures. - -// A subroutine used by the following test. -void TestEq1(int x) { - ASSERT_EQ(1, x); -} - -// This function calls a test subroutine, catches the fatal failure it -// generates, and then returns early. -void TryTestSubroutine() { - // Calls a subrountine that yields a fatal failure. - TestEq1(2); - - // Catches the fatal failure and aborts the test. - // - // The testing::Test:: prefix is necessary when calling - // HasFatalFailure() outside of a TEST, TEST_F, or test fixture. - if (testing::Test::HasFatalFailure()) return; - - // If we get here, something is wrong. - FAIL() << "This should never be reached."; -} - -TEST(PassingTest, PassingTest1) { -} - -TEST(PassingTest, PassingTest2) { -} - -// Tests that parameters of failing parameterized tests are printed in the -// failing test summary. -class FailingParamTest : public testing::TestWithParam {}; - -TEST_P(FailingParamTest, Fails) { - EXPECT_EQ(1, GetParam()); -} - -// This generates a test which will fail. Google Test is expected to print -// its parameter when it outputs the list of all failed tests. -INSTANTIATE_TEST_CASE_P(PrintingFailingParams, - FailingParamTest, - testing::Values(2)); - -static const char kGoldenString[] = "\"Line\0 1\"\nLine 2"; - -TEST(NonfatalFailureTest, EscapesStringOperands) { - std::string actual = "actual \"string\""; - EXPECT_EQ(kGoldenString, actual); - - const char* golden = kGoldenString; - EXPECT_EQ(golden, actual); -} - -TEST(NonfatalFailureTest, DiffForLongStrings) { - std::string golden_str(kGoldenString, sizeof(kGoldenString) - 1); - EXPECT_EQ(golden_str, "Line 2"); -} - -// Tests catching a fatal failure in a subroutine. -TEST(FatalFailureTest, FatalFailureInSubroutine) { - printf("(expecting a failure that x should be 1)\n"); - - TryTestSubroutine(); -} - -// Tests catching a fatal failure in a nested subroutine. -TEST(FatalFailureTest, FatalFailureInNestedSubroutine) { - printf("(expecting a failure that x should be 1)\n"); - - // Calls a subrountine that yields a fatal failure. - TryTestSubroutine(); - - // Catches the fatal failure and aborts the test. - // - // When calling HasFatalFailure() inside a TEST, TEST_F, or test - // fixture, the testing::Test:: prefix is not needed. - if (HasFatalFailure()) return; - - // If we get here, something is wrong. - FAIL() << "This should never be reached."; -} - -// Tests HasFatalFailure() after a failed EXPECT check. -TEST(FatalFailureTest, NonfatalFailureInSubroutine) { - printf("(expecting a failure on false)\n"); - EXPECT_TRUE(false); // Generates a nonfatal failure - ASSERT_FALSE(HasFatalFailure()); // This should succeed. -} - -// Tests interleaving user logging and Google Test assertions. -TEST(LoggingTest, InterleavingLoggingAndAssertions) { - static const int a[4] = { - 3, 9, 2, 6 - }; - - printf("(expecting 2 failures on (3) >= (a[i]))\n"); - for (int i = 0; i < static_cast(sizeof(a)/sizeof(*a)); i++) { - printf("i == %d\n", i); - EXPECT_GE(3, a[i]); - } -} - -// Tests the SCOPED_TRACE macro. - -// A helper function for testing SCOPED_TRACE. -void SubWithoutTrace(int n) { - EXPECT_EQ(1, n); - ASSERT_EQ(2, n); -} - -// Another helper function for testing SCOPED_TRACE. -void SubWithTrace(int n) { - SCOPED_TRACE(testing::Message() << "n = " << n); - - SubWithoutTrace(n); -} - -TEST(SCOPED_TRACETest, AcceptedValues) { - SCOPED_TRACE("literal string"); - SCOPED_TRACE(std::string("std::string")); - SCOPED_TRACE(1337); // streamable type - const char* null_value = NULL; - SCOPED_TRACE(null_value); - - ADD_FAILURE() << "Just checking that all these values work fine."; -} - -// Tests that SCOPED_TRACE() obeys lexical scopes. -TEST(SCOPED_TRACETest, ObeysScopes) { - printf("(expected to fail)\n"); - - // There should be no trace before SCOPED_TRACE() is invoked. - ADD_FAILURE() << "This failure is expected, and shouldn't have a trace."; - - { - SCOPED_TRACE("Expected trace"); - // After SCOPED_TRACE(), a failure in the current scope should contain - // the trace. - ADD_FAILURE() << "This failure is expected, and should have a trace."; - } - - // Once the control leaves the scope of the SCOPED_TRACE(), there - // should be no trace again. - ADD_FAILURE() << "This failure is expected, and shouldn't have a trace."; -} - -// Tests that SCOPED_TRACE works inside a loop. -TEST(SCOPED_TRACETest, WorksInLoop) { - printf("(expected to fail)\n"); - - for (int i = 1; i <= 2; i++) { - SCOPED_TRACE(testing::Message() << "i = " << i); - - SubWithoutTrace(i); - } -} - -// Tests that SCOPED_TRACE works in a subroutine. -TEST(SCOPED_TRACETest, WorksInSubroutine) { - printf("(expected to fail)\n"); - - SubWithTrace(1); - SubWithTrace(2); -} - -// Tests that SCOPED_TRACE can be nested. -TEST(SCOPED_TRACETest, CanBeNested) { - printf("(expected to fail)\n"); - - SCOPED_TRACE(""); // A trace without a message. - - SubWithTrace(2); -} - -// Tests that multiple SCOPED_TRACEs can be used in the same scope. -TEST(SCOPED_TRACETest, CanBeRepeated) { - printf("(expected to fail)\n"); - - SCOPED_TRACE("A"); - ADD_FAILURE() - << "This failure is expected, and should contain trace point A."; - - SCOPED_TRACE("B"); - ADD_FAILURE() - << "This failure is expected, and should contain trace point A and B."; - - { - SCOPED_TRACE("C"); - ADD_FAILURE() << "This failure is expected, and should " - << "contain trace point A, B, and C."; - } - - SCOPED_TRACE("D"); - ADD_FAILURE() << "This failure is expected, and should " - << "contain trace point A, B, and D."; -} - -#if GTEST_IS_THREADSAFE -// Tests that SCOPED_TRACE()s can be used concurrently from multiple -// threads. Namely, an assertion should be affected by -// SCOPED_TRACE()s in its own thread only. - -// Here's the sequence of actions that happen in the test: -// -// Thread A (main) | Thread B (spawned) -// ===============================|================================ -// spawns thread B | -// -------------------------------+-------------------------------- -// waits for n1 | SCOPED_TRACE("Trace B"); -// | generates failure #1 -// | notifies n1 -// -------------------------------+-------------------------------- -// SCOPED_TRACE("Trace A"); | waits for n2 -// generates failure #2 | -// notifies n2 | -// -------------------------------|-------------------------------- -// waits for n3 | generates failure #3 -// | trace B dies -// | generates failure #4 -// | notifies n3 -// -------------------------------|-------------------------------- -// generates failure #5 | finishes -// trace A dies | -// generates failure #6 | -// -------------------------------|-------------------------------- -// waits for thread B to finish | - -struct CheckPoints { - Notification n1; - Notification n2; - Notification n3; -}; - -static void ThreadWithScopedTrace(CheckPoints* check_points) { - { - SCOPED_TRACE("Trace B"); - ADD_FAILURE() - << "Expected failure #1 (in thread B, only trace B alive)."; - check_points->n1.Notify(); - check_points->n2.WaitForNotification(); - - ADD_FAILURE() - << "Expected failure #3 (in thread B, trace A & B both alive)."; - } // Trace B dies here. - ADD_FAILURE() - << "Expected failure #4 (in thread B, only trace A alive)."; - check_points->n3.Notify(); -} - -TEST(SCOPED_TRACETest, WorksConcurrently) { - printf("(expecting 6 failures)\n"); - - CheckPoints check_points; - ThreadWithParam thread(&ThreadWithScopedTrace, - &check_points, - NULL); - check_points.n1.WaitForNotification(); - - { - SCOPED_TRACE("Trace A"); - ADD_FAILURE() - << "Expected failure #2 (in thread A, trace A & B both alive)."; - check_points.n2.Notify(); - check_points.n3.WaitForNotification(); - - ADD_FAILURE() - << "Expected failure #5 (in thread A, only trace A alive)."; - } // Trace A dies here. - ADD_FAILURE() - << "Expected failure #6 (in thread A, no trace alive)."; - thread.Join(); -} -#endif // GTEST_IS_THREADSAFE - -// Tests basic functionality of the ScopedTrace utility (most of its features -// are already tested in SCOPED_TRACETest). -TEST(ScopedTraceTest, WithExplicitFileAndLine) { - testing::ScopedTrace trace("explicit_file.cc", 123, "expected trace message"); - ADD_FAILURE() << "Check that the trace is attached to a particular location."; -} - -TEST(DisabledTestsWarningTest, - DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning) { - // This test body is intentionally empty. Its sole purpose is for - // verifying that the --gtest_also_run_disabled_tests flag - // suppresses the "YOU HAVE 12 DISABLED TESTS" warning at the end of - // the test output. -} - -// Tests using assertions outside of TEST and TEST_F. -// -// This function creates two failures intentionally. -void AdHocTest() { - printf("The non-test part of the code is expected to have 2 failures.\n\n"); - EXPECT_TRUE(false); - EXPECT_EQ(2, 3); -} - -// Runs all TESTs, all TEST_Fs, and the ad hoc test. -int RunAllTests() { - AdHocTest(); - return RUN_ALL_TESTS(); -} - -// Tests non-fatal failures in the fixture constructor. -class NonFatalFailureInFixtureConstructorTest : public testing::Test { - protected: - NonFatalFailureInFixtureConstructorTest() { - printf("(expecting 5 failures)\n"); - ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor."; - } - - ~NonFatalFailureInFixtureConstructorTest() { - ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor."; - } - - virtual void SetUp() { - ADD_FAILURE() << "Expected failure #2, in SetUp()."; - } - - virtual void TearDown() { - ADD_FAILURE() << "Expected failure #4, in TearDown."; - } -}; - -TEST_F(NonFatalFailureInFixtureConstructorTest, FailureInConstructor) { - ADD_FAILURE() << "Expected failure #3, in the test body."; -} - -// Tests fatal failures in the fixture constructor. -class FatalFailureInFixtureConstructorTest : public testing::Test { - protected: - FatalFailureInFixtureConstructorTest() { - printf("(expecting 2 failures)\n"); - Init(); - } - - ~FatalFailureInFixtureConstructorTest() { - ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor."; - } - - virtual void SetUp() { - ADD_FAILURE() << "UNEXPECTED failure in SetUp(). " - << "We should never get here, as the test fixture c'tor " - << "had a fatal failure."; - } - - virtual void TearDown() { - ADD_FAILURE() << "UNEXPECTED failure in TearDown(). " - << "We should never get here, as the test fixture c'tor " - << "had a fatal failure."; - } - - private: - void Init() { - FAIL() << "Expected failure #1, in the test fixture c'tor."; - } -}; - -TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) { - ADD_FAILURE() << "UNEXPECTED failure in the test body. " - << "We should never get here, as the test fixture c'tor " - << "had a fatal failure."; -} - -// Tests non-fatal failures in SetUp(). -class NonFatalFailureInSetUpTest : public testing::Test { - protected: - virtual ~NonFatalFailureInSetUpTest() { - Deinit(); - } - - virtual void SetUp() { - printf("(expecting 4 failures)\n"); - ADD_FAILURE() << "Expected failure #1, in SetUp()."; - } - - virtual void TearDown() { - FAIL() << "Expected failure #3, in TearDown()."; - } - private: - void Deinit() { - FAIL() << "Expected failure #4, in the test fixture d'tor."; - } -}; - -TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) { - FAIL() << "Expected failure #2, in the test function."; -} - -// Tests fatal failures in SetUp(). -class FatalFailureInSetUpTest : public testing::Test { - protected: - virtual ~FatalFailureInSetUpTest() { - Deinit(); - } - - virtual void SetUp() { - printf("(expecting 3 failures)\n"); - FAIL() << "Expected failure #1, in SetUp()."; - } - - virtual void TearDown() { - FAIL() << "Expected failure #2, in TearDown()."; - } - private: - void Deinit() { - FAIL() << "Expected failure #3, in the test fixture d'tor."; - } -}; - -TEST_F(FatalFailureInSetUpTest, FailureInSetUp) { - FAIL() << "UNEXPECTED failure in the test function. " - << "We should never get here, as SetUp() failed."; -} - -TEST(AddFailureAtTest, MessageContainsSpecifiedFileAndLineNumber) { - ADD_FAILURE_AT("foo.cc", 42) << "Expected failure in foo.cc"; -} - -#if GTEST_IS_THREADSAFE - -// A unary function that may die. -void DieIf(bool should_die) { - GTEST_CHECK_(!should_die) << " - death inside DieIf()."; -} - -// Tests running death tests in a multi-threaded context. - -// Used for coordination between the main and the spawn thread. -struct SpawnThreadNotifications { - SpawnThreadNotifications() {} - - Notification spawn_thread_started; - Notification spawn_thread_ok_to_terminate; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(SpawnThreadNotifications); -}; - -// The function to be executed in the thread spawn by the -// MultipleThreads test (below). -static void ThreadRoutine(SpawnThreadNotifications* notifications) { - // Signals the main thread that this thread has started. - notifications->spawn_thread_started.Notify(); - - // Waits for permission to finish from the main thread. - notifications->spawn_thread_ok_to_terminate.WaitForNotification(); -} - -// This is a death-test test, but it's not named with a DeathTest -// suffix. It starts threads which might interfere with later -// death tests, so it must run after all other death tests. -class DeathTestAndMultiThreadsTest : public testing::Test { - protected: - // Starts a thread and waits for it to begin. - virtual void SetUp() { - thread_.reset(new ThreadWithParam( - &ThreadRoutine, ¬ifications_, NULL)); - notifications_.spawn_thread_started.WaitForNotification(); - } - // Tells the thread to finish, and reaps it. - // Depending on the version of the thread library in use, - // a manager thread might still be left running that will interfere - // with later death tests. This is unfortunate, but this class - // cleans up after itself as best it can. - virtual void TearDown() { - notifications_.spawn_thread_ok_to_terminate.Notify(); - } - - private: - SpawnThreadNotifications notifications_; - testing::internal::scoped_ptr > - thread_; -}; - -#endif // GTEST_IS_THREADSAFE - -// The MixedUpTestCaseTest test case verifies that Google Test will fail a -// test if it uses a different fixture class than what other tests in -// the same test case use. It deliberately contains two fixture -// classes with the same name but defined in different namespaces. - -// The MixedUpTestCaseWithSameTestNameTest test case verifies that -// when the user defines two tests with the same test case name AND -// same test name (but in different namespaces), the second test will -// fail. - -namespace foo { - -class MixedUpTestCaseTest : public testing::Test { -}; - -TEST_F(MixedUpTestCaseTest, FirstTestFromNamespaceFoo) {} -TEST_F(MixedUpTestCaseTest, SecondTestFromNamespaceFoo) {} - -class MixedUpTestCaseWithSameTestNameTest : public testing::Test { -}; - -TEST_F(MixedUpTestCaseWithSameTestNameTest, - TheSecondTestWithThisNameShouldFail) {} - -} // namespace foo - -namespace bar { - -class MixedUpTestCaseTest : public testing::Test { -}; - -// The following two tests are expected to fail. We rely on the -// golden file to check that Google Test generates the right error message. -TEST_F(MixedUpTestCaseTest, ThisShouldFail) {} -TEST_F(MixedUpTestCaseTest, ThisShouldFailToo) {} - -class MixedUpTestCaseWithSameTestNameTest : public testing::Test { -}; - -// Expected to fail. We rely on the golden file to check that Google Test -// generates the right error message. -TEST_F(MixedUpTestCaseWithSameTestNameTest, - TheSecondTestWithThisNameShouldFail) {} - -} // namespace bar - -// The following two test cases verify that Google Test catches the user -// error of mixing TEST and TEST_F in the same test case. The first -// test case checks the scenario where TEST_F appears before TEST, and -// the second one checks where TEST appears before TEST_F. - -class TEST_F_before_TEST_in_same_test_case : public testing::Test { -}; - -TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {} - -// Expected to fail. We rely on the golden file to check that Google Test -// generates the right error message. -TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {} - -class TEST_before_TEST_F_in_same_test_case : public testing::Test { -}; - -TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {} - -// Expected to fail. We rely on the golden file to check that Google Test -// generates the right error message. -TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) { -} - -// Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE(). -int global_integer = 0; - -// Tests that EXPECT_NONFATAL_FAILURE() can reference global variables. -TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) { - global_integer = 0; - EXPECT_NONFATAL_FAILURE({ - EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; - }, "Expected non-fatal failure."); -} - -// Tests that EXPECT_NONFATAL_FAILURE() can reference local variables -// (static or not). -TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) { - int m = 0; - static int n; - n = 1; - EXPECT_NONFATAL_FAILURE({ - EXPECT_EQ(m, n) << "Expected non-fatal failure."; - }, "Expected non-fatal failure."); -} - -// Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly -// one non-fatal failure and no fatal failure. -TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) { - EXPECT_NONFATAL_FAILURE({ - ADD_FAILURE() << "Expected non-fatal failure."; - }, "Expected non-fatal failure."); -} - -// Tests that EXPECT_NONFATAL_FAILURE() fails when there is no -// non-fatal failure. -TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) { - printf("(expecting a failure)\n"); - EXPECT_NONFATAL_FAILURE({ - }, ""); -} - -// Tests that EXPECT_NONFATAL_FAILURE() fails when there are two -// non-fatal failures. -TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) { - printf("(expecting a failure)\n"); - EXPECT_NONFATAL_FAILURE({ - ADD_FAILURE() << "Expected non-fatal failure 1."; - ADD_FAILURE() << "Expected non-fatal failure 2."; - }, ""); -} - -// Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal -// failure. -TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) { - printf("(expecting a failure)\n"); - EXPECT_NONFATAL_FAILURE({ - FAIL() << "Expected fatal failure."; - }, ""); -} - -// Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being -// tested returns. -TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) { - printf("(expecting a failure)\n"); - EXPECT_NONFATAL_FAILURE({ - return; - }, ""); -} - -#if GTEST_HAS_EXCEPTIONS - -// Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being -// tested throws. -TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) { - printf("(expecting a failure)\n"); - try { - EXPECT_NONFATAL_FAILURE({ - throw 0; - }, ""); - } catch(int) { // NOLINT - } -} - -#endif // GTEST_HAS_EXCEPTIONS - -// Tests that EXPECT_FATAL_FAILURE() can reference global variables. -TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) { - global_integer = 0; - EXPECT_FATAL_FAILURE({ - ASSERT_EQ(1, global_integer) << "Expected fatal failure."; - }, "Expected fatal failure."); -} - -// Tests that EXPECT_FATAL_FAILURE() can reference local static -// variables. -TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) { - static int n; - n = 1; - EXPECT_FATAL_FAILURE({ - ASSERT_EQ(0, n) << "Expected fatal failure."; - }, "Expected fatal failure."); -} - -// Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly -// one fatal failure and no non-fatal failure. -TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) { - EXPECT_FATAL_FAILURE({ - FAIL() << "Expected fatal failure."; - }, "Expected fatal failure."); -} - -// Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal -// failure. -TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) { - printf("(expecting a failure)\n"); - EXPECT_FATAL_FAILURE({ - }, ""); -} - -// A helper for generating a fatal failure. -void FatalFailure() { - FAIL() << "Expected fatal failure."; -} - -// Tests that EXPECT_FATAL_FAILURE() fails when there are two -// fatal failures. -TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) { - printf("(expecting a failure)\n"); - EXPECT_FATAL_FAILURE({ - FatalFailure(); - FatalFailure(); - }, ""); -} - -// Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal -// failure. -TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) { - printf("(expecting a failure)\n"); - EXPECT_FATAL_FAILURE({ - ADD_FAILURE() << "Expected non-fatal failure."; - }, ""); -} - -// Tests that EXPECT_FATAL_FAILURE() fails when the statement being -// tested returns. -TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) { - printf("(expecting a failure)\n"); - EXPECT_FATAL_FAILURE({ - return; - }, ""); -} - -#if GTEST_HAS_EXCEPTIONS - -// Tests that EXPECT_FATAL_FAILURE() fails when the statement being -// tested throws. -TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) { - printf("(expecting a failure)\n"); - try { - EXPECT_FATAL_FAILURE({ - throw 0; - }, ""); - } catch(int) { // NOLINT - } -} - -#endif // GTEST_HAS_EXCEPTIONS - -// This #ifdef block tests the output of value-parameterized tests. - -std::string ParamNameFunc(const testing::TestParamInfo& info) { - return info.param; -} - -class ParamTest : public testing::TestWithParam { -}; - -TEST_P(ParamTest, Success) { - EXPECT_EQ("a", GetParam()); -} - -TEST_P(ParamTest, Failure) { - EXPECT_EQ("b", GetParam()) << "Expected failure"; -} - -INSTANTIATE_TEST_CASE_P(PrintingStrings, - ParamTest, - testing::Values(std::string("a")), - ParamNameFunc); - -// This #ifdef block tests the output of typed tests. -#if GTEST_HAS_TYPED_TEST - -template -class TypedTest : public testing::Test { -}; - -TYPED_TEST_CASE(TypedTest, testing::Types); - -TYPED_TEST(TypedTest, Success) { - EXPECT_EQ(0, TypeParam()); -} - -TYPED_TEST(TypedTest, Failure) { - EXPECT_EQ(1, TypeParam()) << "Expected failure"; -} - -#endif // GTEST_HAS_TYPED_TEST - -// This #ifdef block tests the output of type-parameterized tests. -#if GTEST_HAS_TYPED_TEST_P - -template -class TypedTestP : public testing::Test { -}; - -TYPED_TEST_CASE_P(TypedTestP); - -TYPED_TEST_P(TypedTestP, Success) { - EXPECT_EQ(0U, TypeParam()); -} - -TYPED_TEST_P(TypedTestP, Failure) { - EXPECT_EQ(1U, TypeParam()) << "Expected failure"; -} - -REGISTER_TYPED_TEST_CASE_P(TypedTestP, Success, Failure); - -typedef testing::Types UnsignedTypes; -INSTANTIATE_TYPED_TEST_CASE_P(Unsigned, TypedTestP, UnsignedTypes); - -#endif // GTEST_HAS_TYPED_TEST_P - -#if GTEST_HAS_DEATH_TEST - -// We rely on the golden file to verify that tests whose test case -// name ends with DeathTest are run first. - -TEST(ADeathTest, ShouldRunFirst) { -} - -# if GTEST_HAS_TYPED_TEST - -// We rely on the golden file to verify that typed tests whose test -// case name ends with DeathTest are run first. - -template -class ATypedDeathTest : public testing::Test { -}; - -typedef testing::Types NumericTypes; -TYPED_TEST_CASE(ATypedDeathTest, NumericTypes); - -TYPED_TEST(ATypedDeathTest, ShouldRunFirst) { -} - -# endif // GTEST_HAS_TYPED_TEST - -# if GTEST_HAS_TYPED_TEST_P - - -// We rely on the golden file to verify that type-parameterized tests -// whose test case name ends with DeathTest are run first. - -template -class ATypeParamDeathTest : public testing::Test { -}; - -TYPED_TEST_CASE_P(ATypeParamDeathTest); - -TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) { -} - -REGISTER_TYPED_TEST_CASE_P(ATypeParamDeathTest, ShouldRunFirst); - -INSTANTIATE_TYPED_TEST_CASE_P(My, ATypeParamDeathTest, NumericTypes); - -# endif // GTEST_HAS_TYPED_TEST_P - -#endif // GTEST_HAS_DEATH_TEST - -// Tests various failure conditions of -// EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}. -class ExpectFailureTest : public testing::Test { - public: // Must be public and not protected due to a bug in g++ 3.4.2. - enum FailureMode { - FATAL_FAILURE, - NONFATAL_FAILURE - }; - static void AddFailure(FailureMode failure) { - if (failure == FATAL_FAILURE) { - FAIL() << "Expected fatal failure."; - } else { - ADD_FAILURE() << "Expected non-fatal failure."; - } - } -}; - -TEST_F(ExpectFailureTest, ExpectFatalFailure) { - // Expected fatal failure, but succeeds. - printf("(expecting 1 failure)\n"); - EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure."); - // Expected fatal failure, but got a non-fatal failure. - printf("(expecting 1 failure)\n"); - EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal " - "failure."); - // Wrong message. - printf("(expecting 1 failure)\n"); - EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Some other fatal failure " - "expected."); -} - -TEST_F(ExpectFailureTest, ExpectNonFatalFailure) { - // Expected non-fatal failure, but succeeds. - printf("(expecting 1 failure)\n"); - EXPECT_NONFATAL_FAILURE(SUCCEED(), "Expected non-fatal failure."); - // Expected non-fatal failure, but got a fatal failure. - printf("(expecting 1 failure)\n"); - EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure."); - // Wrong message. - printf("(expecting 1 failure)\n"); - EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Some other non-fatal " - "failure."); -} - -#if GTEST_IS_THREADSAFE - -class ExpectFailureWithThreadsTest : public ExpectFailureTest { - protected: - static void AddFailureInOtherThread(FailureMode failure) { - ThreadWithParam thread(&AddFailure, failure, NULL); - thread.Join(); - } -}; - -TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailure) { - // We only intercept the current thread. - printf("(expecting 2 failures)\n"); - EXPECT_FATAL_FAILURE(AddFailureInOtherThread(FATAL_FAILURE), - "Expected fatal failure."); -} - -TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailure) { - // We only intercept the current thread. - printf("(expecting 2 failures)\n"); - EXPECT_NONFATAL_FAILURE(AddFailureInOtherThread(NONFATAL_FAILURE), - "Expected non-fatal failure."); -} - -typedef ExpectFailureWithThreadsTest ScopedFakeTestPartResultReporterTest; - -// Tests that the ScopedFakeTestPartResultReporter only catches failures from -// the current thread if it is instantiated with INTERCEPT_ONLY_CURRENT_THREAD. -TEST_F(ScopedFakeTestPartResultReporterTest, InterceptOnlyCurrentThread) { - printf("(expecting 2 failures)\n"); - TestPartResultArray results; - { - ScopedFakeTestPartResultReporter reporter( - ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD, - &results); - AddFailureInOtherThread(FATAL_FAILURE); - AddFailureInOtherThread(NONFATAL_FAILURE); - } - // The two failures should not have been intercepted. - EXPECT_EQ(0, results.size()) << "This shouldn't fail."; -} - -#endif // GTEST_IS_THREADSAFE - -TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) { - // Expected fatal failure, but succeeds. - printf("(expecting 1 failure)\n"); - EXPECT_FATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected fatal failure."); - // Expected fatal failure, but got a non-fatal failure. - printf("(expecting 1 failure)\n"); - EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE), - "Expected non-fatal failure."); - // Wrong message. - printf("(expecting 1 failure)\n"); - EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE), - "Some other fatal failure expected."); -} - -TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) { - // Expected non-fatal failure, but succeeds. - printf("(expecting 1 failure)\n"); - EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal " - "failure."); - // Expected non-fatal failure, but got a fatal failure. - printf("(expecting 1 failure)\n"); - EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE), - "Expected fatal failure."); - // Wrong message. - printf("(expecting 1 failure)\n"); - EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE), - "Some other non-fatal failure."); -} - - -// Two test environments for testing testing::AddGlobalTestEnvironment(). - -class FooEnvironment : public testing::Environment { - public: - virtual void SetUp() { - printf("%s", "FooEnvironment::SetUp() called.\n"); - } - - virtual void TearDown() { - printf("%s", "FooEnvironment::TearDown() called.\n"); - FAIL() << "Expected fatal failure."; - } -}; - -class BarEnvironment : public testing::Environment { - public: - virtual void SetUp() { - printf("%s", "BarEnvironment::SetUp() called.\n"); - } - - virtual void TearDown() { - printf("%s", "BarEnvironment::TearDown() called.\n"); - ADD_FAILURE() << "Expected non-fatal failure."; - } -}; - -// The main function. -// -// The idea is to use Google Test to run all the tests we have defined (some -// of them are intended to fail), and then compare the test results -// with the "golden" file. -int main(int argc, char **argv) { - testing::GTEST_FLAG(print_time) = false; - - // We just run the tests, knowing some of them are intended to fail. - // We will use a separate Python script to compare the output of - // this program with the golden file. - - // It's hard to test InitGoogleTest() directly, as it has many - // global side effects. The following line serves as a sanity test - // for it. - testing::InitGoogleTest(&argc, argv); - bool internal_skip_environment_and_ad_hoc_tests = - std::count(argv, argv + argc, - std::string("internal_skip_environment_and_ad_hoc_tests")) > 0; - -#if GTEST_HAS_DEATH_TEST - if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") { - // Skip the usual output capturing if we're running as the child - // process of an threadsafe-style death test. -# if GTEST_OS_WINDOWS - posix::FReopen("nul:", "w", stdout); -# else - posix::FReopen("/dev/null", "w", stdout); -# endif // GTEST_OS_WINDOWS - return RUN_ALL_TESTS(); - } -#endif // GTEST_HAS_DEATH_TEST - - if (internal_skip_environment_and_ad_hoc_tests) - return RUN_ALL_TESTS(); - - // Registers two global test environments. - // The golden file verifies that they are set up in the order they - // are registered, and torn down in the reverse order. - testing::AddGlobalTestEnvironment(new FooEnvironment); - testing::AddGlobalTestEnvironment(new BarEnvironment); - - return RunAllTests(); -} diff --git a/googletest/test/gtest_output_test_golden_lin.txt b/googletest/test/gtest_output_test_golden_lin.txt deleted file mode 100644 index 02a77a8..0000000 --- a/googletest/test/gtest_output_test_golden_lin.txt +++ /dev/null @@ -1,997 +0,0 @@ -The non-test part of the code is expected to have 2 failures. - -gtest_output_test_.cc:#: Failure -Value of: false - Actual: false -Expected: true -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Expected equality of these values: - 2 - 3 -Stack trace: (omitted) - -[==========] Running 68 tests from 30 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 -[----------] 2 tests from NonfatalFailureTest -[ RUN ] NonfatalFailureTest.EscapesStringOperands -gtest_output_test_.cc:#: Failure -Expected equality of these values: - kGoldenString - Which is: "\"Line" - actual - Which is: "actual \"string\"" -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Expected equality of these values: - golden - Which is: "\"Line" - actual - Which is: "actual \"string\"" -Stack trace: (omitted) - -[ FAILED ] NonfatalFailureTest.EscapesStringOperands -[ RUN ] NonfatalFailureTest.DiffForLongStrings -gtest_output_test_.cc:#: Failure -Expected equality of these values: - golden_str - Which is: "\"Line\0 1\"\nLine 2" - "Line 2" -With diff: -@@ -1,2 @@ --\"Line\0 1\" - Line 2 - -Stack trace: (omitted) - -[ FAILED ] NonfatalFailureTest.DiffForLongStrings -[----------] 3 tests from FatalFailureTest -[ RUN ] FatalFailureTest.FatalFailureInSubroutine -(expecting a failure that x should be 1) -gtest_output_test_.cc:#: Failure -Expected equality of these values: - 1 - x - Which is: 2 -Stack trace: (omitted) - -[ FAILED ] FatalFailureTest.FatalFailureInSubroutine -[ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine -(expecting a failure that x should be 1) -gtest_output_test_.cc:#: Failure -Expected equality of these values: - 1 - x - Which is: 2 -Stack trace: (omitted) - -[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine -[ RUN ] FatalFailureTest.NonfatalFailureInSubroutine -(expecting a failure on false) -gtest_output_test_.cc:#: Failure -Value of: false - Actual: false -Expected: true -Stack trace: (omitted) - -[ 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:#: Failure -Expected: (3) >= (a[i]), actual: 3 vs 9 -Stack trace: (omitted) - -i == 2 -i == 3 -gtest_output_test_.cc:#: Failure -Expected: (3) >= (a[i]), actual: 3 vs 6 -Stack trace: (omitted) - -[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions -[----------] 7 tests from SCOPED_TRACETest -[ RUN ] SCOPED_TRACETest.AcceptedValues -gtest_output_test_.cc:#: Failure -Failed -Just checking that all these values work fine. -Google Test trace: -gtest_output_test_.cc:#: (null) -gtest_output_test_.cc:#: 1337 -gtest_output_test_.cc:#: std::string -gtest_output_test_.cc:#: literal string -Stack trace: (omitted) - -[ FAILED ] SCOPED_TRACETest.AcceptedValues -[ RUN ] SCOPED_TRACETest.ObeysScopes -(expected to fail) -gtest_output_test_.cc:#: Failure -Failed -This failure is expected, and shouldn't have a trace. -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -This failure is expected, and should have a trace. -Google Test trace: -gtest_output_test_.cc:#: Expected trace -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -This failure is expected, and shouldn't have a trace. -Stack trace: (omitted) - -[ FAILED ] SCOPED_TRACETest.ObeysScopes -[ RUN ] SCOPED_TRACETest.WorksInLoop -(expected to fail) -gtest_output_test_.cc:#: Failure -Expected equality of these values: - 2 - n - Which is: 1 -Google Test trace: -gtest_output_test_.cc:#: i = 1 -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Expected equality of these values: - 1 - n - Which is: 2 -Google Test trace: -gtest_output_test_.cc:#: i = 2 -Stack trace: (omitted) - -[ FAILED ] SCOPED_TRACETest.WorksInLoop -[ RUN ] SCOPED_TRACETest.WorksInSubroutine -(expected to fail) -gtest_output_test_.cc:#: Failure -Expected equality of these values: - 2 - n - Which is: 1 -Google Test trace: -gtest_output_test_.cc:#: n = 1 -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Expected equality of these values: - 1 - n - Which is: 2 -Google Test trace: -gtest_output_test_.cc:#: n = 2 -Stack trace: (omitted) - -[ FAILED ] SCOPED_TRACETest.WorksInSubroutine -[ RUN ] SCOPED_TRACETest.CanBeNested -(expected to fail) -gtest_output_test_.cc:#: Failure -Expected equality of these values: - 1 - n - Which is: 2 -Google Test trace: -gtest_output_test_.cc:#: n = 2 -gtest_output_test_.cc:#: -Stack trace: (omitted) - -[ FAILED ] SCOPED_TRACETest.CanBeNested -[ RUN ] SCOPED_TRACETest.CanBeRepeated -(expected to fail) -gtest_output_test_.cc:#: Failure -Failed -This failure is expected, and should contain trace point A. -Google Test trace: -gtest_output_test_.cc:#: A -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -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 -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -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 -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -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 -Stack trace: (omitted) - -[ FAILED ] SCOPED_TRACETest.CanBeRepeated -[ RUN ] SCOPED_TRACETest.WorksConcurrently -(expecting 6 failures) -gtest_output_test_.cc:#: Failure -Failed -Expected failure #1 (in thread B, only trace B alive). -Google Test trace: -gtest_output_test_.cc:#: Trace B -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #2 (in thread A, trace A & B both alive). -Google Test trace: -gtest_output_test_.cc:#: Trace A -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #3 (in thread B, trace A & B both alive). -Google Test trace: -gtest_output_test_.cc:#: Trace B -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #4 (in thread B, only trace A alive). -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #5 (in thread A, only trace A alive). -Google Test trace: -gtest_output_test_.cc:#: Trace A -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #6 (in thread A, no trace alive). -Stack trace: (omitted) - -[ FAILED ] SCOPED_TRACETest.WorksConcurrently -[----------] 1 test from ScopedTraceTest -[ RUN ] ScopedTraceTest.WithExplicitFileAndLine -gtest_output_test_.cc:#: Failure -Failed -Check that the trace is attached to a particular location. -Google Test trace: -explicit_file.cc:123: expected trace message -Stack trace: (omitted) - -[ FAILED ] ScopedTraceTest.WithExplicitFileAndLine -[----------] 1 test from NonFatalFailureInFixtureConstructorTest -[ RUN ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor -(expecting 5 failures) -gtest_output_test_.cc:#: Failure -Failed -Expected failure #1, in the test fixture c'tor. -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #2, in SetUp(). -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #3, in the test body. -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #4, in TearDown. -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #5, in the test fixture d'tor. -Stack trace: (omitted) - -[ FAILED ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor -[----------] 1 test from FatalFailureInFixtureConstructorTest -[ RUN ] FatalFailureInFixtureConstructorTest.FailureInConstructor -(expecting 2 failures) -gtest_output_test_.cc:#: Failure -Failed -Expected failure #1, in the test fixture c'tor. -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #2, in the test fixture d'tor. -Stack trace: (omitted) - -[ FAILED ] FatalFailureInFixtureConstructorTest.FailureInConstructor -[----------] 1 test from NonFatalFailureInSetUpTest -[ RUN ] NonFatalFailureInSetUpTest.FailureInSetUp -(expecting 4 failures) -gtest_output_test_.cc:#: Failure -Failed -Expected failure #1, in SetUp(). -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #2, in the test function. -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #3, in TearDown(). -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #4, in the test fixture d'tor. -Stack trace: (omitted) - -[ FAILED ] NonFatalFailureInSetUpTest.FailureInSetUp -[----------] 1 test from FatalFailureInSetUpTest -[ RUN ] FatalFailureInSetUpTest.FailureInSetUp -(expecting 3 failures) -gtest_output_test_.cc:#: Failure -Failed -Expected failure #1, in SetUp(). -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #2, in TearDown(). -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected failure #3, in the test fixture d'tor. -Stack trace: (omitted) - -[ FAILED ] FatalFailureInSetUpTest.FailureInSetUp -[----------] 1 test from AddFailureAtTest -[ RUN ] AddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber -foo.cc:42: Failure -Failed -Expected failure in foo.cc -Stack trace: (omitted) - -[ FAILED ] AddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber -[----------] 4 tests from MixedUpTestCaseTest -[ RUN ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo -[ OK ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo -[ RUN ] MixedUpTestCaseTest.SecondTestFromNamespaceFoo -[ OK ] MixedUpTestCaseTest.SecondTestFromNamespaceFoo -[ RUN ] MixedUpTestCaseTest.ThisShouldFail -gtest.cc:#: Failure -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. -Stack trace: (omitted) - -[ FAILED ] MixedUpTestCaseTest.ThisShouldFail -[ RUN ] MixedUpTestCaseTest.ThisShouldFailToo -gtest.cc:#: Failure -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. -Stack trace: (omitted) - -[ FAILED ] MixedUpTestCaseTest.ThisShouldFailToo -[----------] 2 tests from MixedUpTestCaseWithSameTestNameTest -[ RUN ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail -[ OK ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail -[ RUN ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail -gtest.cc:#: Failure -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. -Stack trace: (omitted) - -[ 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:#: Failure -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. -Stack trace: (omitted) - -[ 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:#: Failure -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. -Stack trace: (omitted) - -[ 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:#: Failure -Expected: 1 non-fatal failure - Actual: 0 failures -Stack trace: (omitted) - -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure -[ RUN ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures -(expecting a failure) -gtest.cc:#: Failure -Expected: 1 non-fatal failure - Actual: 2 failures -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure 1. -Stack trace: (omitted) - - -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure 2. -Stack trace: (omitted) - - -Stack trace: (omitted) - -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures -[ RUN ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure -(expecting a failure) -gtest.cc:#: Failure -Expected: 1 non-fatal failure - Actual: -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. -Stack trace: (omitted) - - -Stack trace: (omitted) - -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure -[ RUN ] ExpectNonfatalFailureTest.FailsWhenStatementReturns -(expecting a failure) -gtest.cc:#: Failure -Expected: 1 non-fatal failure - Actual: 0 failures -Stack trace: (omitted) - -[ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementReturns -[ RUN ] ExpectNonfatalFailureTest.FailsWhenStatementThrows -(expecting a failure) -gtest.cc:#: Failure -Expected: 1 non-fatal failure - Actual: 0 failures -Stack trace: (omitted) - -[ 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:#: Failure -Expected: 1 fatal failure - Actual: 0 failures -Stack trace: (omitted) - -[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure -[ RUN ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures -(expecting a failure) -gtest.cc:#: Failure -Expected: 1 fatal failure - Actual: 2 failures -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. -Stack trace: (omitted) - - -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. -Stack trace: (omitted) - - -Stack trace: (omitted) - -[ FAILED ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures -[ RUN ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure -(expecting a failure) -gtest.cc:#: Failure -Expected: 1 fatal failure - Actual: -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure. -Stack trace: (omitted) - - -Stack trace: (omitted) - -[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure -[ RUN ] ExpectFatalFailureTest.FailsWhenStatementReturns -(expecting a failure) -gtest.cc:#: Failure -Expected: 1 fatal failure - Actual: 0 failures -Stack trace: (omitted) - -[ FAILED ] ExpectFatalFailureTest.FailsWhenStatementReturns -[ RUN ] ExpectFatalFailureTest.FailsWhenStatementThrows -(expecting a failure) -gtest.cc:#: Failure -Expected: 1 fatal failure - Actual: 0 failures -Stack trace: (omitted) - -[ 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:#: Failure -Expected equality of these values: - 1 - TypeParam() - Which is: 0 -Expected failure -Stack trace: (omitted) - -[ 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:#: Failure -Expected equality of these values: - 1U - Which is: 1 - TypeParam() - Which is: '\0' -Expected failure -Stack trace: (omitted) - -[ 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:#: Failure -Expected equality of these values: - 1U - Which is: 1 - TypeParam() - Which is: 0 -Expected failure -Stack trace: (omitted) - -[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int -[----------] 4 tests from ExpectFailureTest -[ RUN ] ExpectFailureTest.ExpectFatalFailure -(expecting 1 failure) -gtest.cc:#: Failure -Expected: 1 fatal failure - Actual: -gtest_output_test_.cc:#: Success: -Succeeded -Stack trace: (omitted) - - -Stack trace: (omitted) - -(expecting 1 failure) -gtest.cc:#: Failure -Expected: 1 fatal failure - Actual: -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure. -Stack trace: (omitted) - - -Stack trace: (omitted) - -(expecting 1 failure) -gtest.cc:#: Failure -Expected: 1 fatal failure containing "Some other fatal failure expected." - Actual: -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. -Stack trace: (omitted) - - -Stack trace: (omitted) - -[ FAILED ] ExpectFailureTest.ExpectFatalFailure -[ RUN ] ExpectFailureTest.ExpectNonFatalFailure -(expecting 1 failure) -gtest.cc:#: Failure -Expected: 1 non-fatal failure - Actual: -gtest_output_test_.cc:#: Success: -Succeeded -Stack trace: (omitted) - - -Stack trace: (omitted) - -(expecting 1 failure) -gtest.cc:#: Failure -Expected: 1 non-fatal failure - Actual: -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. -Stack trace: (omitted) - - -Stack trace: (omitted) - -(expecting 1 failure) -gtest.cc:#: Failure -Expected: 1 non-fatal failure containing "Some other non-fatal failure." - Actual: -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure. -Stack trace: (omitted) - - -Stack trace: (omitted) - -[ FAILED ] ExpectFailureTest.ExpectNonFatalFailure -[ RUN ] ExpectFailureTest.ExpectFatalFailureOnAllThreads -(expecting 1 failure) -gtest.cc:#: Failure -Expected: 1 fatal failure - Actual: -gtest_output_test_.cc:#: Success: -Succeeded -Stack trace: (omitted) - - -Stack trace: (omitted) - -(expecting 1 failure) -gtest.cc:#: Failure -Expected: 1 fatal failure - Actual: -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure. -Stack trace: (omitted) - - -Stack trace: (omitted) - -(expecting 1 failure) -gtest.cc:#: Failure -Expected: 1 fatal failure containing "Some other fatal failure expected." - Actual: -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. -Stack trace: (omitted) - - -Stack trace: (omitted) - -[ FAILED ] ExpectFailureTest.ExpectFatalFailureOnAllThreads -[ RUN ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads -(expecting 1 failure) -gtest.cc:#: Failure -Expected: 1 non-fatal failure - Actual: -gtest_output_test_.cc:#: Success: -Succeeded -Stack trace: (omitted) - - -Stack trace: (omitted) - -(expecting 1 failure) -gtest.cc:#: Failure -Expected: 1 non-fatal failure - Actual: -gtest_output_test_.cc:#: Fatal failure: -Failed -Expected fatal failure. -Stack trace: (omitted) - - -Stack trace: (omitted) - -(expecting 1 failure) -gtest.cc:#: Failure -Expected: 1 non-fatal failure containing "Some other non-fatal failure." - Actual: -gtest_output_test_.cc:#: Non-fatal failure: -Failed -Expected non-fatal failure. -Stack trace: (omitted) - - -Stack trace: (omitted) - -[ FAILED ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads -[----------] 2 tests from ExpectFailureWithThreadsTest -[ RUN ] ExpectFailureWithThreadsTest.ExpectFatalFailure -(expecting 2 failures) -gtest_output_test_.cc:#: Failure -Failed -Expected fatal failure. -Stack trace: (omitted) - -gtest.cc:#: Failure -Expected: 1 fatal failure - Actual: 0 failures -Stack trace: (omitted) - -[ FAILED ] ExpectFailureWithThreadsTest.ExpectFatalFailure -[ RUN ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure -(expecting 2 failures) -gtest_output_test_.cc:#: Failure -Failed -Expected non-fatal failure. -Stack trace: (omitted) - -gtest.cc:#: Failure -Expected: 1 non-fatal failure - Actual: 0 failures -Stack trace: (omitted) - -[ FAILED ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure -[----------] 1 test from ScopedFakeTestPartResultReporterTest -[ RUN ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread -(expecting 2 failures) -gtest_output_test_.cc:#: Failure -Failed -Expected fatal failure. -Stack trace: (omitted) - -gtest_output_test_.cc:#: Failure -Failed -Expected non-fatal failure. -Stack trace: (omitted) - -[ FAILED ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread -[----------] 1 test from PrintingFailingParams/FailingParamTest -[ RUN ] PrintingFailingParams/FailingParamTest.Fails/0 -gtest_output_test_.cc:#: Failure -Expected equality of these values: - 1 - GetParam() - Which is: 2 -Stack trace: (omitted) - -[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 -[----------] 2 tests from PrintingStrings/ParamTest -[ RUN ] PrintingStrings/ParamTest.Success/a -[ OK ] PrintingStrings/ParamTest.Success/a -[ RUN ] PrintingStrings/ParamTest.Failure/a -gtest_output_test_.cc:#: Failure -Expected equality of these values: - "b" - GetParam() - Which is: "a" -Expected failure -Stack trace: (omitted) - -[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a" -[----------] Global test environment tear-down -BarEnvironment::TearDown() called. -gtest_output_test_.cc:#: Failure -Failed -Expected non-fatal failure. -Stack trace: (omitted) - -FooEnvironment::TearDown() called. -gtest_output_test_.cc:#: Failure -Failed -Expected fatal failure. -Stack trace: (omitted) - -[==========] 68 tests from 30 test cases ran. -[ PASSED ] 22 tests. -[ FAILED ] 46 tests, listed below: -[ FAILED ] NonfatalFailureTest.EscapesStringOperands -[ FAILED ] NonfatalFailureTest.DiffForLongStrings -[ FAILED ] FatalFailureTest.FatalFailureInSubroutine -[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine -[ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine -[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions -[ FAILED ] SCOPED_TRACETest.AcceptedValues -[ FAILED ] SCOPED_TRACETest.ObeysScopes -[ FAILED ] SCOPED_TRACETest.WorksInLoop -[ FAILED ] SCOPED_TRACETest.WorksInSubroutine -[ FAILED ] SCOPED_TRACETest.CanBeNested -[ FAILED ] SCOPED_TRACETest.CanBeRepeated -[ FAILED ] SCOPED_TRACETest.WorksConcurrently -[ FAILED ] ScopedTraceTest.WithExplicitFileAndLine -[ FAILED ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor -[ FAILED ] FatalFailureInFixtureConstructorTest.FailureInConstructor -[ FAILED ] NonFatalFailureInSetUpTest.FailureInSetUp -[ FAILED ] FatalFailureInSetUpTest.FailureInSetUp -[ FAILED ] AddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber -[ 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 ] ExpectFailureWithThreadsTest.ExpectFatalFailure -[ FAILED ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure -[ FAILED ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread -[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 -[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a" - -46 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:#: Failure -Expected equality of these values: - 1 - x - Which is: 2 -Stack trace: (omitted) - -[ FAILED ] FatalFailureTest.FatalFailureInSubroutine (? ms) -[ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine -(expecting a failure that x should be 1) -gtest_output_test_.cc:#: Failure -Expected equality of these values: - 1 - x - Which is: 2 -Stack trace: (omitted) - -[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine (? ms) -[ RUN ] FatalFailureTest.NonfatalFailureInSubroutine -(expecting a failure on false) -gtest_output_test_.cc:#: Failure -Value of: false - Actual: false -Expected: true -Stack trace: (omitted) - -[ 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:#: Failure -Expected: (3) >= (a[i]), actual: 3 vs 9 -Stack trace: (omitted) - -i == 2 -i == 3 -gtest_output_test_.cc:#: Failure -Expected: (3) >= (a[i]), actual: 3 vs 6 -Stack trace: (omitted) - -[ 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 -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 2 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. -- cgit v0.12 From 38486eb03e9f67b2b7edbe63c663fbeb8e7bd57a Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 11:32:08 -0400 Subject: googltest-color-test changes --- googletest/test/BUILD.bazel | 10 +-- googletest/test/googletest-color-test.py | 129 ++++++++++++++++++++++++++++++ googletest/test/googletest-color-test_.cc | 63 +++++++++++++++ googletest/test/gtest_color_test.py | 129 ------------------------------ googletest/test/gtest_color_test_.cc | 63 --------------- 5 files changed, 197 insertions(+), 197 deletions(-) create mode 100755 googletest/test/googletest-color-test.py create mode 100644 googletest/test/googletest-color-test_.cc delete mode 100755 googletest/test/gtest_color_test.py delete mode 100644 googletest/test/gtest_color_test_.cc diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 9f190c0..29361c0 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -197,17 +197,17 @@ py_test( ) cc_binary( - name = "gtest_color_test_", + name = "googletest-color-test_", testonly = 1, - srcs = ["gtest_color_test_.cc"], + srcs = ["googletest-color-test_.cc"], deps = ["//:gtest"], ) py_test( - name = "gtest_color_test", + name = "googletest-color-test", size = "small", - srcs = ["gtest_color_test.py"], - data = [":gtest_color_test_"], + srcs = ["googletest-color-test.py"], + data = [":googletest-color-test_"], deps = [":gtest_test_utils"], ) diff --git a/googletest/test/googletest-color-test.py b/googletest/test/googletest-color-test.py new file mode 100755 index 0000000..875d478 --- /dev/null +++ b/googletest/test/googletest-color-test.py @@ -0,0 +1,129 @@ +#!/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. + +"""Verifies that Google Test correctly determines whether to use colors.""" + +__author__ = 'wan@google.com (Zhanyong Wan)' + +import os +import gtest_test_utils + +IS_WINDOWS = os.name == 'nt' + +COLOR_ENV_VAR = 'GTEST_COLOR' +COLOR_FLAG = 'gtest_color' +COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-color-test_') + + +def SetEnvVar(env_var, value): + """Sets the env variable to 'value'; unsets it when 'value' is None.""" + + if value is not None: + os.environ[env_var] = value + elif env_var in os.environ: + del os.environ[env_var] + + +def UsesColor(term, color_env_var, color_flag): + """Runs googletest-color-test_ and returns its exit code.""" + + SetEnvVar('TERM', term) + SetEnvVar(COLOR_ENV_VAR, color_env_var) + + if color_flag is None: + args = [] + else: + args = ['--%s=%s' % (COLOR_FLAG, color_flag)] + p = gtest_test_utils.Subprocess([COMMAND] + args) + return not p.exited or p.exit_code + + +class GTestColorTest(gtest_test_utils.TestCase): + def testNoEnvVarNoFlag(self): + """Tests the case when there's neither GTEST_COLOR nor --gtest_color.""" + + if not IS_WINDOWS: + self.assert_(not UsesColor('dumb', None, None)) + self.assert_(not UsesColor('emacs', None, None)) + self.assert_(not UsesColor('xterm-mono', None, None)) + self.assert_(not UsesColor('unknown', None, None)) + self.assert_(not UsesColor(None, None, None)) + self.assert_(UsesColor('linux', None, None)) + self.assert_(UsesColor('cygwin', None, None)) + self.assert_(UsesColor('xterm', None, None)) + self.assert_(UsesColor('xterm-color', None, None)) + self.assert_(UsesColor('xterm-256color', None, None)) + + def testFlagOnly(self): + """Tests the case when there's --gtest_color but not GTEST_COLOR.""" + + self.assert_(not UsesColor('dumb', None, 'no')) + self.assert_(not UsesColor('xterm-color', None, 'no')) + if not IS_WINDOWS: + self.assert_(not UsesColor('emacs', None, 'auto')) + self.assert_(UsesColor('xterm', None, 'auto')) + self.assert_(UsesColor('dumb', None, 'yes')) + self.assert_(UsesColor('xterm', None, 'yes')) + + def testEnvVarOnly(self): + """Tests the case when there's GTEST_COLOR but not --gtest_color.""" + + self.assert_(not UsesColor('dumb', 'no', None)) + self.assert_(not UsesColor('xterm-color', 'no', None)) + if not IS_WINDOWS: + self.assert_(not UsesColor('dumb', 'auto', None)) + self.assert_(UsesColor('xterm-color', 'auto', None)) + self.assert_(UsesColor('dumb', 'yes', None)) + self.assert_(UsesColor('xterm-color', 'yes', None)) + + def testEnvVarAndFlag(self): + """Tests the case when there are both GTEST_COLOR and --gtest_color.""" + + self.assert_(not UsesColor('xterm-color', 'no', 'no')) + self.assert_(UsesColor('dumb', 'no', 'yes')) + self.assert_(UsesColor('xterm-color', 'no', 'auto')) + + def testAliasesOfYesAndNo(self): + """Tests using aliases in specifying --gtest_color.""" + + self.assert_(UsesColor('dumb', None, 'true')) + self.assert_(UsesColor('dumb', None, 'YES')) + self.assert_(UsesColor('dumb', None, 'T')) + self.assert_(UsesColor('dumb', None, '1')) + + self.assert_(not UsesColor('xterm', None, 'f')) + self.assert_(not UsesColor('xterm', None, 'false')) + self.assert_(not UsesColor('xterm', None, '0')) + self.assert_(not UsesColor('xterm', None, 'unknown')) + + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/googletest-color-test_.cc b/googletest/test/googletest-color-test_.cc new file mode 100644 index 0000000..f9a21e2 --- /dev/null +++ b/googletest/test/googletest-color-test_.cc @@ -0,0 +1,63 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// A helper program for testing how Google Test determines whether to use +// colors in the output. It prints "YES" and returns 1 if Google Test +// decides to use colors, and prints "NO" and returns 0 otherwise. + +#include + +#include "gtest/gtest.h" +#include "src/gtest-internal-inl.h" + +using testing::internal::ShouldUseColor; + +// The purpose of this is to ensure that the UnitTest singleton is +// created before main() is entered, and thus that ShouldUseColor() +// works the same way as in a real Google-Test-based test. We don't actual +// run the TEST itself. +TEST(GTestColorTest, Dummy) { +} + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + + if (ShouldUseColor(true)) { + // Google Test decides to use colors in the output (assuming it + // goes to a TTY). + printf("YES\n"); + return 1; + } else { + // Google Test decides not to use colors in the output. + printf("NO\n"); + return 0; + } +} diff --git a/googletest/test/gtest_color_test.py b/googletest/test/gtest_color_test.py deleted file mode 100755 index 49b8ed2..0000000 --- a/googletest/test/gtest_color_test.py +++ /dev/null @@ -1,129 +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. - -"""Verifies that Google Test correctly determines whether to use colors.""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import os -import gtest_test_utils - -IS_WINDOWS = os.name == 'nt' - -COLOR_ENV_VAR = 'GTEST_COLOR' -COLOR_FLAG = 'gtest_color' -COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_color_test_') - - -def SetEnvVar(env_var, value): - """Sets the env variable to 'value'; unsets it when 'value' is None.""" - - if value is not None: - os.environ[env_var] = value - elif env_var in os.environ: - del os.environ[env_var] - - -def UsesColor(term, color_env_var, color_flag): - """Runs gtest_color_test_ and returns its exit code.""" - - SetEnvVar('TERM', term) - SetEnvVar(COLOR_ENV_VAR, color_env_var) - - if color_flag is None: - args = [] - else: - args = ['--%s=%s' % (COLOR_FLAG, color_flag)] - p = gtest_test_utils.Subprocess([COMMAND] + args) - return not p.exited or p.exit_code - - -class GTestColorTest(gtest_test_utils.TestCase): - def testNoEnvVarNoFlag(self): - """Tests the case when there's neither GTEST_COLOR nor --gtest_color.""" - - if not IS_WINDOWS: - self.assert_(not UsesColor('dumb', None, None)) - self.assert_(not UsesColor('emacs', None, None)) - self.assert_(not UsesColor('xterm-mono', None, None)) - self.assert_(not UsesColor('unknown', None, None)) - self.assert_(not UsesColor(None, None, None)) - self.assert_(UsesColor('linux', None, None)) - self.assert_(UsesColor('cygwin', None, None)) - self.assert_(UsesColor('xterm', None, None)) - self.assert_(UsesColor('xterm-color', None, None)) - self.assert_(UsesColor('xterm-256color', None, None)) - - def testFlagOnly(self): - """Tests the case when there's --gtest_color but not GTEST_COLOR.""" - - self.assert_(not UsesColor('dumb', None, 'no')) - self.assert_(not UsesColor('xterm-color', None, 'no')) - if not IS_WINDOWS: - self.assert_(not UsesColor('emacs', None, 'auto')) - self.assert_(UsesColor('xterm', None, 'auto')) - self.assert_(UsesColor('dumb', None, 'yes')) - self.assert_(UsesColor('xterm', None, 'yes')) - - def testEnvVarOnly(self): - """Tests the case when there's GTEST_COLOR but not --gtest_color.""" - - self.assert_(not UsesColor('dumb', 'no', None)) - self.assert_(not UsesColor('xterm-color', 'no', None)) - if not IS_WINDOWS: - self.assert_(not UsesColor('dumb', 'auto', None)) - self.assert_(UsesColor('xterm-color', 'auto', None)) - self.assert_(UsesColor('dumb', 'yes', None)) - self.assert_(UsesColor('xterm-color', 'yes', None)) - - def testEnvVarAndFlag(self): - """Tests the case when there are both GTEST_COLOR and --gtest_color.""" - - self.assert_(not UsesColor('xterm-color', 'no', 'no')) - self.assert_(UsesColor('dumb', 'no', 'yes')) - self.assert_(UsesColor('xterm-color', 'no', 'auto')) - - def testAliasesOfYesAndNo(self): - """Tests using aliases in specifying --gtest_color.""" - - self.assert_(UsesColor('dumb', None, 'true')) - self.assert_(UsesColor('dumb', None, 'YES')) - self.assert_(UsesColor('dumb', None, 'T')) - self.assert_(UsesColor('dumb', None, '1')) - - self.assert_(not UsesColor('xterm', None, 'f')) - self.assert_(not UsesColor('xterm', None, 'false')) - self.assert_(not UsesColor('xterm', None, '0')) - self.assert_(not UsesColor('xterm', None, 'unknown')) - - -if __name__ == '__main__': - gtest_test_utils.Main() diff --git a/googletest/test/gtest_color_test_.cc b/googletest/test/gtest_color_test_.cc deleted file mode 100644 index f9a21e2..0000000 --- a/googletest/test/gtest_color_test_.cc +++ /dev/null @@ -1,63 +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. -// -// Author: wan@google.com (Zhanyong Wan) - -// A helper program for testing how Google Test determines whether to use -// colors in the output. It prints "YES" and returns 1 if Google Test -// decides to use colors, and prints "NO" and returns 0 otherwise. - -#include - -#include "gtest/gtest.h" -#include "src/gtest-internal-inl.h" - -using testing::internal::ShouldUseColor; - -// The purpose of this is to ensure that the UnitTest singleton is -// created before main() is entered, and thus that ShouldUseColor() -// works the same way as in a real Google-Test-based test. We don't actual -// run the TEST itself. -TEST(GTestColorTest, Dummy) { -} - -int main(int argc, char** argv) { - testing::InitGoogleTest(&argc, argv); - - if (ShouldUseColor(true)) { - // Google Test decides to use colors in the output (assuming it - // goes to a TTY). - printf("YES\n"); - return 1; - } else { - // Google Test decides not to use colors in the output. - printf("NO\n"); - return 0; - } -} -- cgit v0.12 From d75922ca1c74f50e6a2b018faf435669d4241ca7 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 11:35:13 -0400 Subject: changes for googletest env var test --- googletest/test/BUILD.bazel | 12 +-- googletest/test/googletest-env-var-test.py | 119 ++++++++++++++++++++++++++ googletest/test/googletest-env-var-test_.cc | 124 ++++++++++++++++++++++++++++ googletest/test/gtest_env_var_test.py | 119 -------------------------- googletest/test/gtest_env_var_test_.cc | 124 ---------------------------- 5 files changed, 249 insertions(+), 249 deletions(-) create mode 100755 googletest/test/googletest-env-var-test.py create mode 100644 googletest/test/googletest-env-var-test_.cc delete mode 100755 googletest/test/gtest_env_var_test.py delete mode 100644 googletest/test/gtest_env_var_test_.cc diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 29361c0..0c1eb78 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -212,17 +212,17 @@ py_test( ) cc_binary( - name = "gtest_env_var_test_", + name = "googletest-env-var-test_", testonly = 1, - srcs = ["gtest_env_var_test_.cc"], + srcs = ["googletest-env-var-test_.cc"], deps = ["//:gtest"], ) py_test( - name = "gtest_env_var_test", - size = "small", - srcs = ["gtest_env_var_test.py"], - data = [":gtest_env_var_test_"], + name = "googletest-env-var-test", + size = "medium", + srcs = ["googletest-env-var-test.py"], + data = [":googletest-env-var-test_"], deps = [":gtest_test_utils"], ) diff --git a/googletest/test/googletest-env-var-test.py b/googletest/test/googletest-env-var-test.py new file mode 100755 index 0000000..9c80e2a --- /dev/null +++ b/googletest/test/googletest-env-var-test.py @@ -0,0 +1,119 @@ +#!/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. + +"""Verifies that Google Test correctly parses environment variables.""" + +__author__ = 'wan@google.com (Zhanyong Wan)' + +import os +import gtest_test_utils + + +IS_WINDOWS = os.name == 'nt' +IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' + +COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-env-var-test_') + +environ = os.environ.copy() + + +def AssertEq(expected, actual): + if expected != actual: + print 'Expected: %s' % (expected,) + print ' Actual: %s' % (actual,) + raise AssertionError + + +def SetEnvVar(env_var, value): + """Sets the env variable to 'value'; unsets it when 'value' is None.""" + + if value is not None: + environ[env_var] = value + elif env_var in environ: + del environ[env_var] + + +def GetFlag(flag): + """Runs googletest-env-var-test_ and returns its output.""" + + args = [COMMAND] + if flag is not None: + args += [flag] + return gtest_test_utils.Subprocess(args, env=environ).output + + +def TestFlag(flag, test_val, default_val): + """Verifies that the given flag is affected by the corresponding env var.""" + + env_var = 'GTEST_' + flag.upper() + SetEnvVar(env_var, test_val) + AssertEq(test_val, GetFlag(flag)) + SetEnvVar(env_var, None) + AssertEq(default_val, GetFlag(flag)) + + +class GTestEnvVarTest(gtest_test_utils.TestCase): + + def testEnvVarAffectsFlag(self): + """Tests that environment variable should affect the corresponding flag.""" + + TestFlag('break_on_failure', '1', '0') + TestFlag('color', 'yes', 'auto') + TestFlag('filter', 'FooTest.Bar', '*') + SetEnvVar('XML_OUTPUT_FILE', None) # For 'output' test + TestFlag('output', 'xml:tmp/foo.xml', '') + TestFlag('print_time', '0', '1') + TestFlag('repeat', '999', '1') + TestFlag('throw_on_failure', '1', '0') + TestFlag('death_test_style', 'threadsafe', 'fast') + TestFlag('catch_exceptions', '0', '1') + + if IS_LINUX: + TestFlag('death_test_use_fork', '1', '0') + TestFlag('stack_trace_depth', '0', '100') + + + def testXmlOutputFile(self): + """Tests that $XML_OUTPUT_FILE affects the output flag.""" + + SetEnvVar('GTEST_OUTPUT', None) + SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml') + AssertEq('xml:tmp/bar.xml', GetFlag('output')) + + def testXmlOutputFileOverride(self): + """Tests that $XML_OUTPUT_FILE is overridden by $GTEST_OUTPUT.""" + + SetEnvVar('GTEST_OUTPUT', 'xml:tmp/foo.xml') + SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml') + AssertEq('xml:tmp/foo.xml', GetFlag('output')) + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/googletest-env-var-test_.cc b/googletest/test/googletest-env-var-test_.cc new file mode 100644 index 0000000..74b9506 --- /dev/null +++ b/googletest/test/googletest-env-var-test_.cc @@ -0,0 +1,124 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// A helper program for testing that Google Test parses the environment +// variables correctly. + +#include "gtest/gtest.h" + +#include + +#include "src/gtest-internal-inl.h" + +using ::std::cout; + +namespace testing { + +// The purpose of this is to make the test more realistic by ensuring +// that the UnitTest singleton is created before main() is entered. +// We don't actual run the TEST itself. +TEST(GTestEnvVarTest, Dummy) { +} + +void PrintFlag(const char* flag) { + if (strcmp(flag, "break_on_failure") == 0) { + cout << GTEST_FLAG(break_on_failure); + return; + } + + if (strcmp(flag, "catch_exceptions") == 0) { + cout << GTEST_FLAG(catch_exceptions); + return; + } + + if (strcmp(flag, "color") == 0) { + cout << GTEST_FLAG(color); + return; + } + + if (strcmp(flag, "death_test_style") == 0) { + cout << GTEST_FLAG(death_test_style); + return; + } + + if (strcmp(flag, "death_test_use_fork") == 0) { + cout << GTEST_FLAG(death_test_use_fork); + return; + } + + if (strcmp(flag, "filter") == 0) { + cout << GTEST_FLAG(filter); + return; + } + + if (strcmp(flag, "output") == 0) { + cout << GTEST_FLAG(output); + return; + } + + if (strcmp(flag, "print_time") == 0) { + cout << GTEST_FLAG(print_time); + return; + } + + if (strcmp(flag, "repeat") == 0) { + cout << GTEST_FLAG(repeat); + return; + } + + if (strcmp(flag, "stack_trace_depth") == 0) { + cout << GTEST_FLAG(stack_trace_depth); + return; + } + + if (strcmp(flag, "throw_on_failure") == 0) { + cout << GTEST_FLAG(throw_on_failure); + return; + } + + cout << "Invalid flag name " << flag + << ". Valid names are break_on_failure, color, filter, etc.\n"; + exit(1); +} + +} // namespace testing + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + + if (argc != 2) { + cout << "Usage: googletest-env-var-test_ NAME_OF_FLAG\n"; + return 1; + } + + testing::PrintFlag(argv[1]); + return 0; +} diff --git a/googletest/test/gtest_env_var_test.py b/googletest/test/gtest_env_var_test.py deleted file mode 100755 index beb2a8b..0000000 --- a/googletest/test/gtest_env_var_test.py +++ /dev/null @@ -1,119 +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. - -"""Verifies that Google Test correctly parses environment variables.""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import os -import gtest_test_utils - - -IS_WINDOWS = os.name == 'nt' -IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' - -COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_env_var_test_') - -environ = os.environ.copy() - - -def AssertEq(expected, actual): - if expected != actual: - print 'Expected: %s' % (expected,) - print ' Actual: %s' % (actual,) - raise AssertionError - - -def SetEnvVar(env_var, value): - """Sets the env variable to 'value'; unsets it when 'value' is None.""" - - if value is not None: - environ[env_var] = value - elif env_var in environ: - del environ[env_var] - - -def GetFlag(flag): - """Runs gtest_env_var_test_ and returns its output.""" - - args = [COMMAND] - if flag is not None: - args += [flag] - return gtest_test_utils.Subprocess(args, env=environ).output - - -def TestFlag(flag, test_val, default_val): - """Verifies that the given flag is affected by the corresponding env var.""" - - env_var = 'GTEST_' + flag.upper() - SetEnvVar(env_var, test_val) - AssertEq(test_val, GetFlag(flag)) - SetEnvVar(env_var, None) - AssertEq(default_val, GetFlag(flag)) - - -class GTestEnvVarTest(gtest_test_utils.TestCase): - - def testEnvVarAffectsFlag(self): - """Tests that environment variable should affect the corresponding flag.""" - - TestFlag('break_on_failure', '1', '0') - TestFlag('color', 'yes', 'auto') - TestFlag('filter', 'FooTest.Bar', '*') - SetEnvVar('XML_OUTPUT_FILE', None) # For 'output' test - TestFlag('output', 'xml:tmp/foo.xml', '') - TestFlag('print_time', '0', '1') - TestFlag('repeat', '999', '1') - TestFlag('throw_on_failure', '1', '0') - TestFlag('death_test_style', 'threadsafe', 'fast') - TestFlag('catch_exceptions', '0', '1') - - if IS_LINUX: - TestFlag('death_test_use_fork', '1', '0') - TestFlag('stack_trace_depth', '0', '100') - - - def testXmlOutputFile(self): - """Tests that $XML_OUTPUT_FILE affects the output flag.""" - - SetEnvVar('GTEST_OUTPUT', None) - SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml') - AssertEq('xml:tmp/bar.xml', GetFlag('output')) - - def testXmlOutputFileOverride(self): - """Tests that $XML_OUTPUT_FILE is overridden by $GTEST_OUTPUT.""" - - SetEnvVar('GTEST_OUTPUT', 'xml:tmp/foo.xml') - SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml') - AssertEq('xml:tmp/foo.xml', GetFlag('output')) - -if __name__ == '__main__': - gtest_test_utils.Main() diff --git a/googletest/test/gtest_env_var_test_.cc b/googletest/test/gtest_env_var_test_.cc deleted file mode 100644 index 9b668dc..0000000 --- a/googletest/test/gtest_env_var_test_.cc +++ /dev/null @@ -1,124 +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. -// -// Author: wan@google.com (Zhanyong Wan) - -// A helper program for testing that Google Test parses the environment -// variables correctly. - -#include "gtest/gtest.h" - -#include - -#include "src/gtest-internal-inl.h" - -using ::std::cout; - -namespace testing { - -// The purpose of this is to make the test more realistic by ensuring -// that the UnitTest singleton is created before main() is entered. -// We don't actual run the TEST itself. -TEST(GTestEnvVarTest, Dummy) { -} - -void PrintFlag(const char* flag) { - if (strcmp(flag, "break_on_failure") == 0) { - cout << GTEST_FLAG(break_on_failure); - return; - } - - if (strcmp(flag, "catch_exceptions") == 0) { - cout << GTEST_FLAG(catch_exceptions); - return; - } - - if (strcmp(flag, "color") == 0) { - cout << GTEST_FLAG(color); - return; - } - - if (strcmp(flag, "death_test_style") == 0) { - cout << GTEST_FLAG(death_test_style); - return; - } - - if (strcmp(flag, "death_test_use_fork") == 0) { - cout << GTEST_FLAG(death_test_use_fork); - return; - } - - if (strcmp(flag, "filter") == 0) { - cout << GTEST_FLAG(filter); - return; - } - - if (strcmp(flag, "output") == 0) { - cout << GTEST_FLAG(output); - return; - } - - if (strcmp(flag, "print_time") == 0) { - cout << GTEST_FLAG(print_time); - return; - } - - if (strcmp(flag, "repeat") == 0) { - cout << GTEST_FLAG(repeat); - return; - } - - if (strcmp(flag, "stack_trace_depth") == 0) { - cout << GTEST_FLAG(stack_trace_depth); - return; - } - - if (strcmp(flag, "throw_on_failure") == 0) { - cout << GTEST_FLAG(throw_on_failure); - return; - } - - cout << "Invalid flag name " << flag - << ". Valid names are break_on_failure, color, filter, etc.\n"; - exit(1); -} - -} // namespace testing - -int main(int argc, char** argv) { - testing::InitGoogleTest(&argc, argv); - - if (argc != 2) { - cout << "Usage: gtest_env_var_test_ NAME_OF_FLAG\n"; - return 1; - } - - testing::PrintFlag(argv[1]); - return 0; -} -- cgit v0.12 From a28968d6982f03ce21eb74f96068e7838d3e9e05 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 11:46:43 -0400 Subject: changes to googletest break on failure and googletest filter unittests --- googletest/test/BUILD.bazel | 39 +- .../test/googletest-break-on-failure-unittest.py | 210 +++++++ .../test/googletest-break-on-failure-unittest_.cc | 87 +++ googletest/test/googletest-filter-unittest.py | 638 +++++++++++++++++++++ googletest/test/googletest-filter-unittest_.cc | 138 +++++ .../test/googletest-throw-on-failure-test.py | 171 ++++++ .../test/googletest-throw-on-failure-test_.cc | 72 +++ googletest/test/gtest_break_on_failure_unittest.py | 210 ------- .../test/gtest_break_on_failure_unittest_.cc | 87 --- googletest/test/gtest_filter_unittest.py | 638 --------------------- googletest/test/gtest_filter_unittest_.cc | 138 ----- googletest/test/gtest_throw_on_failure_test.py | 171 ------ googletest/test/gtest_throw_on_failure_test_.cc | 72 --- 13 files changed, 1339 insertions(+), 1332 deletions(-) create mode 100755 googletest/test/googletest-break-on-failure-unittest.py create mode 100644 googletest/test/googletest-break-on-failure-unittest_.cc create mode 100755 googletest/test/googletest-filter-unittest.py create mode 100644 googletest/test/googletest-filter-unittest_.cc create mode 100755 googletest/test/googletest-throw-on-failure-test.py create mode 100644 googletest/test/googletest-throw-on-failure-test_.cc delete mode 100755 googletest/test/gtest_break_on_failure_unittest.py delete mode 100644 googletest/test/gtest_break_on_failure_unittest_.cc delete mode 100755 googletest/test/gtest_filter_unittest.py delete mode 100644 googletest/test/gtest_filter_unittest_.cc delete mode 100755 googletest/test/gtest_throw_on_failure_test.py delete mode 100644 googletest/test/gtest_throw_on_failure_test_.cc diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 0c1eb78..090c463 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -227,35 +227,39 @@ py_test( ) cc_binary( - name = "gtest_filter_unittest_", + name = "googletest-filter-unittest_", testonly = 1, - srcs = ["gtest_filter_unittest_.cc"], + srcs = ["googletest-filter-unittest_.cc"], deps = ["//:gtest"], ) py_test( - name = "gtest_filter_unittest", - size = "small", - srcs = ["gtest_filter_unittest.py"], - data = [":gtest_filter_unittest_"], + name = "googletest-filter-unittest", + size = "medium", + srcs = ["googletest-filter-unittest.py"], + data = [":googletest-filter-unittest_"], deps = [":gtest_test_utils"], ) + cc_binary( - name = "gtest_break_on_failure_unittest_", + name = "googletest-break-on-failure-unittest_", testonly = 1, - srcs = ["gtest_break_on_failure_unittest_.cc"], + srcs = ["googletest-break-on-failure-unittest_.cc"], deps = ["//:gtest"], ) + + py_test( - name = "gtest_break_on_failure_unittest", + name = "googletest-break-on-failure-unittest", size = "small", - srcs = ["gtest_break_on_failure_unittest.py"], - data = [":gtest_break_on_failure_unittest_"], + srcs = ["googletest-break-on-failure-unittest.py"], + data = [":googletest-break-on-failure-unittest_"], deps = [":gtest_test_utils"], ) + cc_test( name = "gtest_assert_by_exception_test", size = "small", @@ -263,21 +267,24 @@ cc_test( deps = ["//:gtest"], ) + + cc_binary( - name = "gtest_throw_on_failure_test_", + name = "googletest-throw-on-failure-test_", testonly = 1, - srcs = ["gtest_throw_on_failure_test_.cc"], + srcs = ["googletest-throw-on-failure-test_.cc"], deps = ["//:gtest"], ) py_test( - name = "gtest_throw_on_failure_test", + name = "googletest-throw-on-failure-test", size = "small", - srcs = ["gtest_throw_on_failure_test.py"], - data = [":gtest_throw_on_failure_test_"], + srcs = ["googletest-throw-on-failure-test.py"], + data = [":googletest-throw-on-failure-test_"], deps = [":gtest_test_utils"], ) + cc_binary( name = "gtest_list_tests_unittest_", testonly = 1, diff --git a/googletest/test/googletest-break-on-failure-unittest.py b/googletest/test/googletest-break-on-failure-unittest.py new file mode 100755 index 0000000..cd77547 --- /dev/null +++ b/googletest/test/googletest-break-on-failure-unittest.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python +# +# Copyright 2006, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Unit test for Google Test's break-on-failure mode. + +A user can ask Google Test to seg-fault when an assertion fails, using +either the GTEST_BREAK_ON_FAILURE environment variable or the +--gtest_break_on_failure flag. This script tests such functionality +by invoking googletest-break-on-failure-unittest_ (a program written with +Google Test) with different environments and command line flags. +""" + +__author__ = 'wan@google.com (Zhanyong Wan)' + +import os +import gtest_test_utils + +# Constants. + +IS_WINDOWS = os.name == 'nt' + +# The environment variable for enabling/disabling the break-on-failure mode. +BREAK_ON_FAILURE_ENV_VAR = 'GTEST_BREAK_ON_FAILURE' + +# The command line flag for enabling/disabling the break-on-failure mode. +BREAK_ON_FAILURE_FLAG = 'gtest_break_on_failure' + +# The environment variable for enabling/disabling the throw-on-failure mode. +THROW_ON_FAILURE_ENV_VAR = 'GTEST_THROW_ON_FAILURE' + +# The environment variable for enabling/disabling the catch-exceptions mode. +CATCH_EXCEPTIONS_ENV_VAR = 'GTEST_CATCH_EXCEPTIONS' + +# Path to the googletest-break-on-failure-unittest_ program. +EXE_PATH = gtest_test_utils.GetTestExecutablePath( + 'googletest-break-on-failure-unittest_') + + +environ = gtest_test_utils.environ +SetEnvVar = gtest_test_utils.SetEnvVar + +# Tests in this file run a Google-Test-based test program and expect it +# to terminate prematurely. Therefore they are incompatible with +# the premature-exit-file protocol by design. Unset the +# premature-exit filepath to prevent Google Test from creating +# the file. +SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None) + + +def Run(command): + """Runs a command; returns 1 if it was killed by a signal, or 0 otherwise.""" + + p = gtest_test_utils.Subprocess(command, env=environ) + if p.terminated_by_signal: + return 1 + else: + return 0 + + +# The tests. + + +class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase): + """Tests using the GTEST_BREAK_ON_FAILURE environment variable or + the --gtest_break_on_failure flag to turn assertion failures into + segmentation faults. + """ + + def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault): + """Runs googletest-break-on-failure-unittest_ and verifies that it does + (or does not) have a seg-fault. + + Args: + env_var_value: value of the GTEST_BREAK_ON_FAILURE environment + variable; None if the variable should be unset. + flag_value: value of the --gtest_break_on_failure flag; + None if the flag should not be present. + expect_seg_fault: 1 if the program is expected to generate a seg-fault; + 0 otherwise. + """ + + SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, env_var_value) + + if env_var_value is None: + env_var_value_msg = ' is not set' + else: + env_var_value_msg = '=' + env_var_value + + if flag_value is None: + flag = '' + elif flag_value == '0': + flag = '--%s=0' % BREAK_ON_FAILURE_FLAG + else: + flag = '--%s' % BREAK_ON_FAILURE_FLAG + + command = [EXE_PATH] + if flag: + command.append(flag) + + if expect_seg_fault: + should_or_not = 'should' + else: + should_or_not = 'should not' + + has_seg_fault = Run(command) + + SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, None) + + msg = ('when %s%s, an assertion failure in "%s" %s cause a seg-fault.' % + (BREAK_ON_FAILURE_ENV_VAR, env_var_value_msg, ' '.join(command), + should_or_not)) + self.assert_(has_seg_fault == expect_seg_fault, msg) + + def testDefaultBehavior(self): + """Tests the behavior of the default mode.""" + + self.RunAndVerify(env_var_value=None, + flag_value=None, + expect_seg_fault=0) + + def testEnvVar(self): + """Tests using the GTEST_BREAK_ON_FAILURE environment variable.""" + + self.RunAndVerify(env_var_value='0', + flag_value=None, + expect_seg_fault=0) + self.RunAndVerify(env_var_value='1', + flag_value=None, + expect_seg_fault=1) + + def testFlag(self): + """Tests using the --gtest_break_on_failure flag.""" + + self.RunAndVerify(env_var_value=None, + flag_value='0', + expect_seg_fault=0) + self.RunAndVerify(env_var_value=None, + flag_value='1', + expect_seg_fault=1) + + def testFlagOverridesEnvVar(self): + """Tests that the flag overrides the environment variable.""" + + self.RunAndVerify(env_var_value='0', + flag_value='0', + expect_seg_fault=0) + self.RunAndVerify(env_var_value='0', + flag_value='1', + expect_seg_fault=1) + self.RunAndVerify(env_var_value='1', + flag_value='0', + expect_seg_fault=0) + self.RunAndVerify(env_var_value='1', + flag_value='1', + expect_seg_fault=1) + + def testBreakOnFailureOverridesThrowOnFailure(self): + """Tests that gtest_break_on_failure overrides gtest_throw_on_failure.""" + + SetEnvVar(THROW_ON_FAILURE_ENV_VAR, '1') + try: + self.RunAndVerify(env_var_value=None, + flag_value='1', + expect_seg_fault=1) + finally: + SetEnvVar(THROW_ON_FAILURE_ENV_VAR, None) + + if IS_WINDOWS: + def testCatchExceptionsDoesNotInterfere(self): + """Tests that gtest_catch_exceptions doesn't interfere.""" + + SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, '1') + try: + self.RunAndVerify(env_var_value='1', + flag_value='1', + expect_seg_fault=1) + finally: + SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, None) + + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/googletest-break-on-failure-unittest_.cc b/googletest/test/googletest-break-on-failure-unittest_.cc new file mode 100644 index 0000000..1231ec2 --- /dev/null +++ b/googletest/test/googletest-break-on-failure-unittest_.cc @@ -0,0 +1,87 @@ +// Copyright 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Unit test for Google Test's break-on-failure mode. +// +// A user can ask Google Test to seg-fault when an assertion fails, using +// either the GTEST_BREAK_ON_FAILURE environment variable or the +// --gtest_break_on_failure flag. This file is used for testing such +// functionality. +// +// This program will be invoked from a Python unit test. It is +// expected to fail. Don't run it directly. + +#include "gtest/gtest.h" + +#if GTEST_OS_WINDOWS +# include +# include +#endif + +namespace { + +// A test that's expected to fail. +TEST(Foo, Bar) { + EXPECT_EQ(2, 3); +} + +#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE +// On Windows Mobile global exception handlers are not supported. +LONG WINAPI ExitWithExceptionCode( + struct _EXCEPTION_POINTERS* exception_pointers) { + exit(exception_pointers->ExceptionRecord->ExceptionCode); +} +#endif + +} // namespace + +int main(int argc, char **argv) { +#if GTEST_OS_WINDOWS + // Suppresses display of the Windows error dialog upon encountering + // a general protection fault (segment violation). + SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS); + +# 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 + // if the application is compiled in debug mode. Thus we use our own + // filter which always exits with the exception code for unhandled + // exceptions. + SetUnhandledExceptionFilter(ExitWithExceptionCode); + +# endif +#endif // GTEST_OS_WINDOWS + testing::InitGoogleTest(&argc, argv); + + return RUN_ALL_TESTS(); +} diff --git a/googletest/test/googletest-filter-unittest.py b/googletest/test/googletest-filter-unittest.py new file mode 100755 index 0000000..1e554d5 --- /dev/null +++ b/googletest/test/googletest-filter-unittest.py @@ -0,0 +1,638 @@ +#!/usr/bin/env python +# +# Copyright 2005 Google Inc. All Rights Reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Unit test for Google Test test filters. + +A user can specify which test(s) in a Google Test program to run via either +the GTEST_FILTER environment variable or the --gtest_filter flag. +This script tests such functionality by invoking +googletest-filter-unittest_ (a program written with Google Test) with different +environments and command line flags. + +Note that test sharding may also influence which tests are filtered. Therefore, +we test that here also. +""" + +__author__ = 'wan@google.com (Zhanyong Wan)' + +import os +import re +import sets +import sys +import gtest_test_utils + +# Constants. + +# Checks if this platform can pass empty environment variables to child +# processes. We set an env variable to an empty string and invoke a python +# script in a subprocess to print whether the variable is STILL in +# os.environ. We then use 'eval' to parse the child's output so that an +# exception is thrown if the input is anything other than 'True' nor 'False'. +CAN_PASS_EMPTY_ENV = False +if sys.executable: + os.environ['EMPTY_VAR'] = '' + child = gtest_test_utils.Subprocess( + [sys.executable, '-c', 'import os; print \'EMPTY_VAR\' in os.environ']) + CAN_PASS_EMPTY_ENV = eval(child.output) + + +# Check if this platform can unset environment variables in child processes. +# We set an env variable to a non-empty string, unset it, and invoke +# a python script in a subprocess to print whether the variable +# is NO LONGER in os.environ. +# We use 'eval' to parse the child's output so that an exception +# is thrown if the input is neither 'True' nor 'False'. +CAN_UNSET_ENV = False +if sys.executable: + os.environ['UNSET_VAR'] = 'X' + del os.environ['UNSET_VAR'] + child = gtest_test_utils.Subprocess( + [sys.executable, '-c', 'import os; print \'UNSET_VAR\' not in os.environ' + ]) + CAN_UNSET_ENV = eval(child.output) + + +# Checks if we should test with an empty filter. This doesn't +# make sense on platforms that cannot pass empty env variables (Win32) +# and on platforms that cannot unset variables (since we cannot tell +# the difference between "" and NULL -- Borland and Solaris < 5.10) +CAN_TEST_EMPTY_FILTER = (CAN_PASS_EMPTY_ENV and CAN_UNSET_ENV) + + +# The environment variable for specifying the test filters. +FILTER_ENV_VAR = 'GTEST_FILTER' + +# The environment variables for test sharding. +TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS' +SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX' +SHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE' + +# The command line flag for specifying the test filters. +FILTER_FLAG = 'gtest_filter' + +# The command line flag for including disabled tests. +ALSO_RUN_DISABLED_TESTS_FLAG = 'gtest_also_run_disabled_tests' + +# Command to run the googletest-filter-unittest_ program. +COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-filter-unittest_') + +# Regex for determining whether parameterized tests are enabled in the binary. +PARAM_TEST_REGEX = re.compile(r'/ParamTest') + +# Regex for parsing test case names from Google Test's output. +TEST_CASE_REGEX = re.compile(r'^\[\-+\] \d+ tests? from (\w+(/\w+)?)') + +# Regex for parsing test names from Google Test's output. +TEST_REGEX = re.compile(r'^\[\s*RUN\s*\].*\.(\w+(/\w+)?)') + +# The command line flag to tell Google Test to output the list of tests it +# will run. +LIST_TESTS_FLAG = '--gtest_list_tests' + +# Indicates whether Google Test supports death tests. +SUPPORTS_DEATH_TESTS = 'HasDeathTest' in gtest_test_utils.Subprocess( + [COMMAND, LIST_TESTS_FLAG]).output + +# Full names of all tests in googletest-filter-unittests_. +PARAM_TESTS = [ + 'SeqP/ParamTest.TestX/0', + 'SeqP/ParamTest.TestX/1', + 'SeqP/ParamTest.TestY/0', + 'SeqP/ParamTest.TestY/1', + 'SeqQ/ParamTest.TestX/0', + 'SeqQ/ParamTest.TestX/1', + 'SeqQ/ParamTest.TestY/0', + 'SeqQ/ParamTest.TestY/1', + ] + +DISABLED_TESTS = [ + 'BarTest.DISABLED_TestFour', + 'BarTest.DISABLED_TestFive', + 'BazTest.DISABLED_TestC', + 'DISABLED_FoobarTest.Test1', + 'DISABLED_FoobarTest.DISABLED_Test2', + 'DISABLED_FoobarbazTest.TestA', + ] + +if SUPPORTS_DEATH_TESTS: + DEATH_TESTS = [ + 'HasDeathTest.Test1', + 'HasDeathTest.Test2', + ] +else: + DEATH_TESTS = [] + +# All the non-disabled tests. +ACTIVE_TESTS = [ + 'FooTest.Abc', + 'FooTest.Xyz', + + 'BarTest.TestOne', + 'BarTest.TestTwo', + 'BarTest.TestThree', + + 'BazTest.TestOne', + 'BazTest.TestA', + 'BazTest.TestB', + ] + DEATH_TESTS + PARAM_TESTS + +param_tests_present = None + +# Utilities. + +environ = os.environ.copy() + + +def SetEnvVar(env_var, value): + """Sets the env variable to 'value'; unsets it when 'value' is None.""" + + if value is not None: + environ[env_var] = value + elif env_var in environ: + del environ[env_var] + + +def RunAndReturnOutput(args = None): + """Runs the test program and returns its output.""" + + return gtest_test_utils.Subprocess([COMMAND] + (args or []), + env=environ).output + + +def RunAndExtractTestList(args = None): + """Runs the test program and returns its exit code and a list of tests run.""" + + p = gtest_test_utils.Subprocess([COMMAND] + (args or []), env=environ) + tests_run = [] + test_case = '' + test = '' + for line in p.output.split('\n'): + match = TEST_CASE_REGEX.match(line) + if match is not None: + test_case = match.group(1) + else: + match = TEST_REGEX.match(line) + if match is not None: + test = match.group(1) + tests_run.append(test_case + '.' + test) + return (tests_run, p.exit_code) + + +def InvokeWithModifiedEnv(extra_env, function, *args, **kwargs): + """Runs the given function and arguments in a modified environment.""" + try: + original_env = environ.copy() + environ.update(extra_env) + return function(*args, **kwargs) + finally: + environ.clear() + environ.update(original_env) + + +def RunWithSharding(total_shards, shard_index, command): + """Runs a test program shard and returns exit code and a list of tests run.""" + + extra_env = {SHARD_INDEX_ENV_VAR: str(shard_index), + TOTAL_SHARDS_ENV_VAR: str(total_shards)} + return InvokeWithModifiedEnv(extra_env, RunAndExtractTestList, command) + +# The unit test. + + +class GTestFilterUnitTest(gtest_test_utils.TestCase): + """Tests the env variable or the command line flag to filter tests.""" + + # Utilities. + + def AssertSetEqual(self, lhs, rhs): + """Asserts that two sets are equal.""" + + for elem in lhs: + self.assert_(elem in rhs, '%s in %s' % (elem, rhs)) + + for elem in rhs: + self.assert_(elem in lhs, '%s in %s' % (elem, lhs)) + + def AssertPartitionIsValid(self, set_var, list_of_sets): + """Asserts that list_of_sets is a valid partition of set_var.""" + + full_partition = [] + for slice_var in list_of_sets: + full_partition.extend(slice_var) + self.assertEqual(len(set_var), len(full_partition)) + self.assertEqual(sets.Set(set_var), sets.Set(full_partition)) + + def AdjustForParameterizedTests(self, tests_to_run): + """Adjust tests_to_run in case value parameterized tests are disabled.""" + + global param_tests_present + if not param_tests_present: + return list(sets.Set(tests_to_run) - sets.Set(PARAM_TESTS)) + else: + return tests_to_run + + def RunAndVerify(self, gtest_filter, tests_to_run): + """Checks that the binary runs correct set of tests for a given filter.""" + + tests_to_run = self.AdjustForParameterizedTests(tests_to_run) + + # First, tests using the environment variable. + + # Windows removes empty variables from the environment when passing it + # to a new process. This means it is impossible to pass an empty filter + # into a process using the environment variable. However, we can still + # test the case when the variable is not supplied (i.e., gtest_filter is + # None). + # pylint: disable-msg=C6403 + if CAN_TEST_EMPTY_FILTER or gtest_filter != '': + SetEnvVar(FILTER_ENV_VAR, gtest_filter) + tests_run = RunAndExtractTestList()[0] + SetEnvVar(FILTER_ENV_VAR, None) + self.AssertSetEqual(tests_run, tests_to_run) + # pylint: enable-msg=C6403 + + # Next, tests using the command line flag. + + if gtest_filter is None: + args = [] + else: + args = ['--%s=%s' % (FILTER_FLAG, gtest_filter)] + + tests_run = RunAndExtractTestList(args)[0] + self.AssertSetEqual(tests_run, tests_to_run) + + def RunAndVerifyWithSharding(self, gtest_filter, total_shards, tests_to_run, + args=None, check_exit_0=False): + """Checks that binary runs correct tests for the given filter and shard. + + Runs all shards of googletest-filter-unittest_ with the given filter, and + verifies that the right set of tests were run. The union of tests run + on each shard should be identical to tests_to_run, without duplicates. + If check_exit_0, . + + Args: + gtest_filter: A filter to apply to the tests. + total_shards: A total number of shards to split test run into. + tests_to_run: A set of tests expected to run. + args : Arguments to pass to the to the test binary. + check_exit_0: When set to a true value, make sure that all shards + return 0. + """ + + tests_to_run = self.AdjustForParameterizedTests(tests_to_run) + + # Windows removes empty variables from the environment when passing it + # to a new process. This means it is impossible to pass an empty filter + # into a process using the environment variable. However, we can still + # test the case when the variable is not supplied (i.e., gtest_filter is + # None). + # pylint: disable-msg=C6403 + if CAN_TEST_EMPTY_FILTER or gtest_filter != '': + SetEnvVar(FILTER_ENV_VAR, gtest_filter) + partition = [] + for i in range(0, total_shards): + (tests_run, exit_code) = RunWithSharding(total_shards, i, args) + if check_exit_0: + self.assertEqual(0, exit_code) + partition.append(tests_run) + + self.AssertPartitionIsValid(tests_to_run, partition) + SetEnvVar(FILTER_ENV_VAR, None) + # pylint: enable-msg=C6403 + + def RunAndVerifyAllowingDisabled(self, gtest_filter, tests_to_run): + """Checks that the binary runs correct set of tests for the given filter. + + Runs googletest-filter-unittest_ with the given filter, and enables + disabled tests. Verifies that the right set of tests were run. + + Args: + gtest_filter: A filter to apply to the tests. + tests_to_run: A set of tests expected to run. + """ + + tests_to_run = self.AdjustForParameterizedTests(tests_to_run) + + # Construct the command line. + args = ['--%s' % ALSO_RUN_DISABLED_TESTS_FLAG] + if gtest_filter is not None: + args.append('--%s=%s' % (FILTER_FLAG, gtest_filter)) + + tests_run = RunAndExtractTestList(args)[0] + self.AssertSetEqual(tests_run, tests_to_run) + + def setUp(self): + """Sets up test case. + + Determines whether value-parameterized tests are enabled in the binary and + sets the flags accordingly. + """ + + global param_tests_present + if param_tests_present is None: + param_tests_present = PARAM_TEST_REGEX.search( + RunAndReturnOutput()) is not None + + def testDefaultBehavior(self): + """Tests the behavior of not specifying the filter.""" + + self.RunAndVerify(None, ACTIVE_TESTS) + + def testDefaultBehaviorWithShards(self): + """Tests the behavior without the filter, with sharding enabled.""" + + self.RunAndVerifyWithSharding(None, 1, ACTIVE_TESTS) + self.RunAndVerifyWithSharding(None, 2, ACTIVE_TESTS) + self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS) - 1, ACTIVE_TESTS) + self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS), ACTIVE_TESTS) + self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS) + 1, ACTIVE_TESTS) + + def testEmptyFilter(self): + """Tests an empty filter.""" + + self.RunAndVerify('', []) + self.RunAndVerifyWithSharding('', 1, []) + self.RunAndVerifyWithSharding('', 2, []) + + def testBadFilter(self): + """Tests a filter that matches nothing.""" + + self.RunAndVerify('BadFilter', []) + self.RunAndVerifyAllowingDisabled('BadFilter', []) + + def testFullName(self): + """Tests filtering by full name.""" + + self.RunAndVerify('FooTest.Xyz', ['FooTest.Xyz']) + self.RunAndVerifyAllowingDisabled('FooTest.Xyz', ['FooTest.Xyz']) + self.RunAndVerifyWithSharding('FooTest.Xyz', 5, ['FooTest.Xyz']) + + def testUniversalFilters(self): + """Tests filters that match everything.""" + + self.RunAndVerify('*', ACTIVE_TESTS) + self.RunAndVerify('*.*', ACTIVE_TESTS) + self.RunAndVerifyWithSharding('*.*', len(ACTIVE_TESTS) - 3, ACTIVE_TESTS) + self.RunAndVerifyAllowingDisabled('*', ACTIVE_TESTS + DISABLED_TESTS) + self.RunAndVerifyAllowingDisabled('*.*', ACTIVE_TESTS + DISABLED_TESTS) + + def testFilterByTestCase(self): + """Tests filtering by test case name.""" + + self.RunAndVerify('FooTest.*', ['FooTest.Abc', 'FooTest.Xyz']) + + BAZ_TESTS = ['BazTest.TestOne', 'BazTest.TestA', 'BazTest.TestB'] + self.RunAndVerify('BazTest.*', BAZ_TESTS) + self.RunAndVerifyAllowingDisabled('BazTest.*', + BAZ_TESTS + ['BazTest.DISABLED_TestC']) + + def testFilterByTest(self): + """Tests filtering by test name.""" + + self.RunAndVerify('*.TestOne', ['BarTest.TestOne', 'BazTest.TestOne']) + + def testFilterDisabledTests(self): + """Select only the disabled tests to run.""" + + self.RunAndVerify('DISABLED_FoobarTest.Test1', []) + self.RunAndVerifyAllowingDisabled('DISABLED_FoobarTest.Test1', + ['DISABLED_FoobarTest.Test1']) + + self.RunAndVerify('*DISABLED_*', []) + self.RunAndVerifyAllowingDisabled('*DISABLED_*', DISABLED_TESTS) + + self.RunAndVerify('*.DISABLED_*', []) + self.RunAndVerifyAllowingDisabled('*.DISABLED_*', [ + 'BarTest.DISABLED_TestFour', + 'BarTest.DISABLED_TestFive', + 'BazTest.DISABLED_TestC', + 'DISABLED_FoobarTest.DISABLED_Test2', + ]) + + self.RunAndVerify('DISABLED_*', []) + self.RunAndVerifyAllowingDisabled('DISABLED_*', [ + 'DISABLED_FoobarTest.Test1', + 'DISABLED_FoobarTest.DISABLED_Test2', + 'DISABLED_FoobarbazTest.TestA', + ]) + + def testWildcardInTestCaseName(self): + """Tests using wildcard in the test case name.""" + + self.RunAndVerify('*a*.*', [ + 'BarTest.TestOne', + 'BarTest.TestTwo', + 'BarTest.TestThree', + + 'BazTest.TestOne', + 'BazTest.TestA', + 'BazTest.TestB', ] + DEATH_TESTS + PARAM_TESTS) + + def testWildcardInTestName(self): + """Tests using wildcard in the test name.""" + + self.RunAndVerify('*.*A*', ['FooTest.Abc', 'BazTest.TestA']) + + def testFilterWithoutDot(self): + """Tests a filter that has no '.' in it.""" + + self.RunAndVerify('*z*', [ + 'FooTest.Xyz', + + 'BazTest.TestOne', + 'BazTest.TestA', + 'BazTest.TestB', + ]) + + def testTwoPatterns(self): + """Tests filters that consist of two patterns.""" + + self.RunAndVerify('Foo*.*:*A*', [ + 'FooTest.Abc', + 'FooTest.Xyz', + + 'BazTest.TestA', + ]) + + # An empty pattern + a non-empty one + self.RunAndVerify(':*A*', ['FooTest.Abc', 'BazTest.TestA']) + + def testThreePatterns(self): + """Tests filters that consist of three patterns.""" + + self.RunAndVerify('*oo*:*A*:*One', [ + 'FooTest.Abc', + 'FooTest.Xyz', + + 'BarTest.TestOne', + + 'BazTest.TestOne', + 'BazTest.TestA', + ]) + + # The 2nd pattern is empty. + self.RunAndVerify('*oo*::*One', [ + 'FooTest.Abc', + 'FooTest.Xyz', + + 'BarTest.TestOne', + + 'BazTest.TestOne', + ]) + + # The last 2 patterns are empty. + self.RunAndVerify('*oo*::', [ + 'FooTest.Abc', + 'FooTest.Xyz', + ]) + + def testNegativeFilters(self): + self.RunAndVerify('*-BazTest.TestOne', [ + 'FooTest.Abc', + 'FooTest.Xyz', + + 'BarTest.TestOne', + 'BarTest.TestTwo', + 'BarTest.TestThree', + + 'BazTest.TestA', + 'BazTest.TestB', + ] + DEATH_TESTS + PARAM_TESTS) + + self.RunAndVerify('*-FooTest.Abc:BazTest.*', [ + 'FooTest.Xyz', + + 'BarTest.TestOne', + 'BarTest.TestTwo', + 'BarTest.TestThree', + ] + DEATH_TESTS + PARAM_TESTS) + + self.RunAndVerify('BarTest.*-BarTest.TestOne', [ + 'BarTest.TestTwo', + 'BarTest.TestThree', + ]) + + # Tests without leading '*'. + self.RunAndVerify('-FooTest.Abc:FooTest.Xyz:BazTest.*', [ + 'BarTest.TestOne', + 'BarTest.TestTwo', + 'BarTest.TestThree', + ] + DEATH_TESTS + PARAM_TESTS) + + # Value parameterized tests. + self.RunAndVerify('*/*', PARAM_TESTS) + + # Value parameterized tests filtering by the sequence name. + self.RunAndVerify('SeqP/*', [ + 'SeqP/ParamTest.TestX/0', + 'SeqP/ParamTest.TestX/1', + 'SeqP/ParamTest.TestY/0', + 'SeqP/ParamTest.TestY/1', + ]) + + # Value parameterized tests filtering by the test name. + self.RunAndVerify('*/0', [ + 'SeqP/ParamTest.TestX/0', + 'SeqP/ParamTest.TestY/0', + 'SeqQ/ParamTest.TestX/0', + 'SeqQ/ParamTest.TestY/0', + ]) + + def testFlagOverridesEnvVar(self): + """Tests that the filter flag overrides the filtering env. variable.""" + + SetEnvVar(FILTER_ENV_VAR, 'Foo*') + args = ['--%s=%s' % (FILTER_FLAG, '*One')] + tests_run = RunAndExtractTestList(args)[0] + SetEnvVar(FILTER_ENV_VAR, None) + + self.AssertSetEqual(tests_run, ['BarTest.TestOne', 'BazTest.TestOne']) + + def testShardStatusFileIsCreated(self): + """Tests that the shard file is created if specified in the environment.""" + + shard_status_file = os.path.join(gtest_test_utils.GetTempDir(), + 'shard_status_file') + self.assert_(not os.path.exists(shard_status_file)) + + extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file} + try: + InvokeWithModifiedEnv(extra_env, RunAndReturnOutput) + finally: + self.assert_(os.path.exists(shard_status_file)) + os.remove(shard_status_file) + + def testShardStatusFileIsCreatedWithListTests(self): + """Tests that the shard file is created with the "list_tests" flag.""" + + shard_status_file = os.path.join(gtest_test_utils.GetTempDir(), + 'shard_status_file2') + self.assert_(not os.path.exists(shard_status_file)) + + extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file} + try: + output = InvokeWithModifiedEnv(extra_env, + RunAndReturnOutput, + [LIST_TESTS_FLAG]) + finally: + # This assertion ensures that Google Test enumerated the tests as + # opposed to running them. + self.assert_('[==========]' not in output, + 'Unexpected output during test enumeration.\n' + 'Please ensure that LIST_TESTS_FLAG is assigned the\n' + 'correct flag value for listing Google Test tests.') + + self.assert_(os.path.exists(shard_status_file)) + os.remove(shard_status_file) + + if SUPPORTS_DEATH_TESTS: + def testShardingWorksWithDeathTests(self): + """Tests integration with death tests and sharding.""" + + gtest_filter = 'HasDeathTest.*:SeqP/*' + expected_tests = [ + 'HasDeathTest.Test1', + 'HasDeathTest.Test2', + + 'SeqP/ParamTest.TestX/0', + 'SeqP/ParamTest.TestX/1', + 'SeqP/ParamTest.TestY/0', + 'SeqP/ParamTest.TestY/1', + ] + + for flag in ['--gtest_death_test_style=threadsafe', + '--gtest_death_test_style=fast']: + self.RunAndVerifyWithSharding(gtest_filter, 3, expected_tests, + check_exit_0=True, args=[flag]) + self.RunAndVerifyWithSharding(gtest_filter, 5, expected_tests, + check_exit_0=True, args=[flag]) + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/googletest-filter-unittest_.cc b/googletest/test/googletest-filter-unittest_.cc new file mode 100644 index 0000000..e74a7a3 --- /dev/null +++ b/googletest/test/googletest-filter-unittest_.cc @@ -0,0 +1,138 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Unit test for Google Test test filters. +// +// A user can specify which test(s) in a Google Test program to run via +// either the GTEST_FILTER environment variable or the --gtest_filter +// flag. This is used for testing such functionality. +// +// The program will be invoked from a Python unit test. Don't run it +// directly. + +#include "gtest/gtest.h" + +namespace { + +// Test case FooTest. + +class FooTest : public testing::Test { +}; + +TEST_F(FooTest, Abc) { +} + +TEST_F(FooTest, Xyz) { + FAIL() << "Expected failure."; +} + +// Test case BarTest. + +TEST(BarTest, TestOne) { +} + +TEST(BarTest, TestTwo) { +} + +TEST(BarTest, TestThree) { +} + +TEST(BarTest, DISABLED_TestFour) { + FAIL() << "Expected failure."; +} + +TEST(BarTest, DISABLED_TestFive) { + FAIL() << "Expected failure."; +} + +// Test case BazTest. + +TEST(BazTest, TestOne) { + FAIL() << "Expected failure."; +} + +TEST(BazTest, TestA) { +} + +TEST(BazTest, TestB) { +} + +TEST(BazTest, DISABLED_TestC) { + FAIL() << "Expected failure."; +} + +// Test case HasDeathTest + +TEST(HasDeathTest, Test1) { + EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); +} + +// We need at least two death tests to make sure that the all death tests +// aren't on the first shard. +TEST(HasDeathTest, Test2) { + EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); +} + +// Test case FoobarTest + +TEST(DISABLED_FoobarTest, Test1) { + FAIL() << "Expected failure."; +} + +TEST(DISABLED_FoobarTest, DISABLED_Test2) { + FAIL() << "Expected failure."; +} + +// Test case FoobarbazTest + +TEST(DISABLED_FoobarbazTest, TestA) { + FAIL() << "Expected failure."; +} + +class ParamTest : public testing::TestWithParam { +}; + +TEST_P(ParamTest, TestX) { +} + +TEST_P(ParamTest, TestY) { +} + +INSTANTIATE_TEST_CASE_P(SeqP, ParamTest, testing::Values(1, 2)); +INSTANTIATE_TEST_CASE_P(SeqQ, ParamTest, testing::Values(5, 6)); + +} // namespace + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + + return RUN_ALL_TESTS(); +} diff --git a/googletest/test/googletest-throw-on-failure-test.py b/googletest/test/googletest-throw-on-failure-test.py new file mode 100755 index 0000000..7253cfd --- /dev/null +++ b/googletest/test/googletest-throw-on-failure-test.py @@ -0,0 +1,171 @@ +#!/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 Google Test's throw-on-failure mode with exceptions disabled. + +This script invokes googletest-throw-on-failure-test_ (a program written with +Google Test) with different environments and command line flags. +""" + +__author__ = 'wan@google.com (Zhanyong Wan)' + +import os +import gtest_test_utils + + +# Constants. + +# The command line flag for enabling/disabling the throw-on-failure mode. +THROW_ON_FAILURE = 'gtest_throw_on_failure' + +# Path to the googletest-throw-on-failure-test_ program, compiled with +# exceptions disabled. +EXE_PATH = gtest_test_utils.GetTestExecutablePath( + 'googletest-throw-on-failure-test_') + + +# Utilities. + + +def SetEnvVar(env_var, value): + """Sets an environment variable to a given value; unsets it when the + given value is None. + """ + + env_var = env_var.upper() + if value is not None: + os.environ[env_var] = value + elif env_var in os.environ: + del os.environ[env_var] + + +def Run(command): + """Runs a command; returns True/False if its exit code is/isn't 0.""" + + print 'Running "%s". . .' % ' '.join(command) + p = gtest_test_utils.Subprocess(command) + return p.exited and p.exit_code == 0 + + +# The tests. TODO(wan@google.com): refactor the class to share common +# logic with code in gtest_break_on_failure_unittest.py. +class ThrowOnFailureTest(gtest_test_utils.TestCase): + """Tests the throw-on-failure mode.""" + + def RunAndVerify(self, env_var_value, flag_value, should_fail): + """Runs googletest-throw-on-failure-test_ and verifies that it does + (or does not) exit with a non-zero code. + + Args: + env_var_value: value of the GTEST_BREAK_ON_FAILURE environment + variable; None if the variable should be unset. + flag_value: value of the --gtest_break_on_failure flag; + None if the flag should not be present. + should_fail: True iff the program is expected to fail. + """ + + SetEnvVar(THROW_ON_FAILURE, env_var_value) + + if env_var_value is None: + env_var_value_msg = ' is not set' + else: + env_var_value_msg = '=' + env_var_value + + if flag_value is None: + flag = '' + elif flag_value == '0': + flag = '--%s=0' % THROW_ON_FAILURE + else: + flag = '--%s' % THROW_ON_FAILURE + + command = [EXE_PATH] + if flag: + command.append(flag) + + if should_fail: + should_or_not = 'should' + else: + should_or_not = 'should not' + + failed = not Run(command) + + SetEnvVar(THROW_ON_FAILURE, None) + + msg = ('when %s%s, an assertion failure in "%s" %s cause a non-zero ' + 'exit code.' % + (THROW_ON_FAILURE, env_var_value_msg, ' '.join(command), + should_or_not)) + self.assert_(failed == should_fail, msg) + + def testDefaultBehavior(self): + """Tests the behavior of the default mode.""" + + self.RunAndVerify(env_var_value=None, flag_value=None, should_fail=False) + + def testThrowOnFailureEnvVar(self): + """Tests using the GTEST_THROW_ON_FAILURE environment variable.""" + + self.RunAndVerify(env_var_value='0', + flag_value=None, + should_fail=False) + self.RunAndVerify(env_var_value='1', + flag_value=None, + should_fail=True) + + def testThrowOnFailureFlag(self): + """Tests using the --gtest_throw_on_failure flag.""" + + self.RunAndVerify(env_var_value=None, + flag_value='0', + should_fail=False) + self.RunAndVerify(env_var_value=None, + flag_value='1', + should_fail=True) + + def testThrowOnFailureFlagOverridesEnvVar(self): + """Tests that --gtest_throw_on_failure overrides GTEST_THROW_ON_FAILURE.""" + + self.RunAndVerify(env_var_value='0', + flag_value='0', + should_fail=False) + self.RunAndVerify(env_var_value='0', + flag_value='1', + should_fail=True) + self.RunAndVerify(env_var_value='1', + flag_value='0', + should_fail=False) + self.RunAndVerify(env_var_value='1', + flag_value='1', + should_fail=True) + + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/googletest-throw-on-failure-test_.cc b/googletest/test/googletest-throw-on-failure-test_.cc new file mode 100644 index 0000000..0617c27 --- /dev/null +++ b/googletest/test/googletest-throw-on-failure-test_.cc @@ -0,0 +1,72 @@ +// Copyright 2009, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Tests Google Test's throw-on-failure mode with exceptions disabled. +// +// This program must be compiled with exceptions disabled. It will be +// invoked by googletest-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 // for fflush, fprintf, NULL, etc. +#include // for exit +#include // for set_terminate + +// 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(1); +} + +int main(int argc, char** argv) { +#if GTEST_HAS_EXCEPTIONS + std::set_terminate(&TerminateHandler); +#endif + testing::InitGoogleTest(&argc, argv); + + // We want to ensure that people can use Google Test assertions in + // other testing frameworks, as long as they initialize Google Test + // properly and set the throw-on-failure mode. Therefore, we don't + // use Google Test's constructs for defining and running tests + // (e.g. TEST and RUN_ALL_TESTS) here. + + // In the throw-on-failure mode with exceptions disabled, this + // assertion will cause the program to exit with a non-zero code. + EXPECT_EQ(2, 3); + + // When not in the throw-on-failure mode, the control will reach + // here. + return 0; +} diff --git a/googletest/test/gtest_break_on_failure_unittest.py b/googletest/test/gtest_break_on_failure_unittest.py deleted file mode 100755 index 16e19db..0000000 --- a/googletest/test/gtest_break_on_failure_unittest.py +++ /dev/null @@ -1,210 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2006, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Unit test for Google Test's break-on-failure mode. - -A user can ask Google Test to seg-fault when an assertion fails, using -either the GTEST_BREAK_ON_FAILURE environment variable or the ---gtest_break_on_failure flag. This script tests such functionality -by invoking gtest_break_on_failure_unittest_ (a program written with -Google Test) with different environments and command line flags. -""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import os -import gtest_test_utils - -# Constants. - -IS_WINDOWS = os.name == 'nt' - -# The environment variable for enabling/disabling the break-on-failure mode. -BREAK_ON_FAILURE_ENV_VAR = 'GTEST_BREAK_ON_FAILURE' - -# The command line flag for enabling/disabling the break-on-failure mode. -BREAK_ON_FAILURE_FLAG = 'gtest_break_on_failure' - -# The environment variable for enabling/disabling the throw-on-failure mode. -THROW_ON_FAILURE_ENV_VAR = 'GTEST_THROW_ON_FAILURE' - -# The environment variable for enabling/disabling the catch-exceptions mode. -CATCH_EXCEPTIONS_ENV_VAR = 'GTEST_CATCH_EXCEPTIONS' - -# Path to the gtest_break_on_failure_unittest_ program. -EXE_PATH = gtest_test_utils.GetTestExecutablePath( - 'gtest_break_on_failure_unittest_') - - -environ = gtest_test_utils.environ -SetEnvVar = gtest_test_utils.SetEnvVar - -# Tests in this file run a Google-Test-based test program and expect it -# to terminate prematurely. Therefore they are incompatible with -# the premature-exit-file protocol by design. Unset the -# premature-exit filepath to prevent Google Test from creating -# the file. -SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None) - - -def Run(command): - """Runs a command; returns 1 if it was killed by a signal, or 0 otherwise.""" - - p = gtest_test_utils.Subprocess(command, env=environ) - if p.terminated_by_signal: - return 1 - else: - return 0 - - -# The tests. - - -class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase): - """Tests using the GTEST_BREAK_ON_FAILURE environment variable or - the --gtest_break_on_failure flag to turn assertion failures into - segmentation faults. - """ - - def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault): - """Runs gtest_break_on_failure_unittest_ and verifies that it does - (or does not) have a seg-fault. - - Args: - env_var_value: value of the GTEST_BREAK_ON_FAILURE environment - variable; None if the variable should be unset. - flag_value: value of the --gtest_break_on_failure flag; - None if the flag should not be present. - expect_seg_fault: 1 if the program is expected to generate a seg-fault; - 0 otherwise. - """ - - SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, env_var_value) - - if env_var_value is None: - env_var_value_msg = ' is not set' - else: - env_var_value_msg = '=' + env_var_value - - if flag_value is None: - flag = '' - elif flag_value == '0': - flag = '--%s=0' % BREAK_ON_FAILURE_FLAG - else: - flag = '--%s' % BREAK_ON_FAILURE_FLAG - - command = [EXE_PATH] - if flag: - command.append(flag) - - if expect_seg_fault: - should_or_not = 'should' - else: - should_or_not = 'should not' - - has_seg_fault = Run(command) - - SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, None) - - msg = ('when %s%s, an assertion failure in "%s" %s cause a seg-fault.' % - (BREAK_ON_FAILURE_ENV_VAR, env_var_value_msg, ' '.join(command), - should_or_not)) - self.assert_(has_seg_fault == expect_seg_fault, msg) - - def testDefaultBehavior(self): - """Tests the behavior of the default mode.""" - - self.RunAndVerify(env_var_value=None, - flag_value=None, - expect_seg_fault=0) - - def testEnvVar(self): - """Tests using the GTEST_BREAK_ON_FAILURE environment variable.""" - - self.RunAndVerify(env_var_value='0', - flag_value=None, - expect_seg_fault=0) - self.RunAndVerify(env_var_value='1', - flag_value=None, - expect_seg_fault=1) - - def testFlag(self): - """Tests using the --gtest_break_on_failure flag.""" - - self.RunAndVerify(env_var_value=None, - flag_value='0', - expect_seg_fault=0) - self.RunAndVerify(env_var_value=None, - flag_value='1', - expect_seg_fault=1) - - def testFlagOverridesEnvVar(self): - """Tests that the flag overrides the environment variable.""" - - self.RunAndVerify(env_var_value='0', - flag_value='0', - expect_seg_fault=0) - self.RunAndVerify(env_var_value='0', - flag_value='1', - expect_seg_fault=1) - self.RunAndVerify(env_var_value='1', - flag_value='0', - expect_seg_fault=0) - self.RunAndVerify(env_var_value='1', - flag_value='1', - expect_seg_fault=1) - - def testBreakOnFailureOverridesThrowOnFailure(self): - """Tests that gtest_break_on_failure overrides gtest_throw_on_failure.""" - - SetEnvVar(THROW_ON_FAILURE_ENV_VAR, '1') - try: - self.RunAndVerify(env_var_value=None, - flag_value='1', - expect_seg_fault=1) - finally: - SetEnvVar(THROW_ON_FAILURE_ENV_VAR, None) - - if IS_WINDOWS: - def testCatchExceptionsDoesNotInterfere(self): - """Tests that gtest_catch_exceptions doesn't interfere.""" - - SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, '1') - try: - self.RunAndVerify(env_var_value='1', - flag_value='1', - expect_seg_fault=1) - finally: - SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, None) - - -if __name__ == '__main__': - gtest_test_utils.Main() diff --git a/googletest/test/gtest_break_on_failure_unittest_.cc b/googletest/test/gtest_break_on_failure_unittest_.cc deleted file mode 100644 index 1231ec2..0000000 --- a/googletest/test/gtest_break_on_failure_unittest_.cc +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) - -// Unit test for Google Test's break-on-failure mode. -// -// A user can ask Google Test to seg-fault when an assertion fails, using -// either the GTEST_BREAK_ON_FAILURE environment variable or the -// --gtest_break_on_failure flag. This file is used for testing such -// functionality. -// -// This program will be invoked from a Python unit test. It is -// expected to fail. Don't run it directly. - -#include "gtest/gtest.h" - -#if GTEST_OS_WINDOWS -# include -# include -#endif - -namespace { - -// A test that's expected to fail. -TEST(Foo, Bar) { - EXPECT_EQ(2, 3); -} - -#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE -// On Windows Mobile global exception handlers are not supported. -LONG WINAPI ExitWithExceptionCode( - struct _EXCEPTION_POINTERS* exception_pointers) { - exit(exception_pointers->ExceptionRecord->ExceptionCode); -} -#endif - -} // namespace - -int main(int argc, char **argv) { -#if GTEST_OS_WINDOWS - // Suppresses display of the Windows error dialog upon encountering - // a general protection fault (segment violation). - SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS); - -# 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 - // if the application is compiled in debug mode. Thus we use our own - // filter which always exits with the exception code for unhandled - // exceptions. - SetUnhandledExceptionFilter(ExitWithExceptionCode); - -# endif -#endif // GTEST_OS_WINDOWS - testing::InitGoogleTest(&argc, argv); - - return RUN_ALL_TESTS(); -} diff --git a/googletest/test/gtest_filter_unittest.py b/googletest/test/gtest_filter_unittest.py deleted file mode 100755 index 92cc77c..0000000 --- a/googletest/test/gtest_filter_unittest.py +++ /dev/null @@ -1,638 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2005 Google Inc. All Rights Reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Unit test for Google Test test filters. - -A user can specify which test(s) in a Google Test program to run via either -the GTEST_FILTER environment variable or the --gtest_filter flag. -This script tests such functionality by invoking -gtest_filter_unittest_ (a program written with Google Test) with different -environments and command line flags. - -Note that test sharding may also influence which tests are filtered. Therefore, -we test that here also. -""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import os -import re -import sets -import sys -import gtest_test_utils - -# Constants. - -# Checks if this platform can pass empty environment variables to child -# processes. We set an env variable to an empty string and invoke a python -# script in a subprocess to print whether the variable is STILL in -# os.environ. We then use 'eval' to parse the child's output so that an -# exception is thrown if the input is anything other than 'True' nor 'False'. -CAN_PASS_EMPTY_ENV = False -if sys.executable: - os.environ['EMPTY_VAR'] = '' - child = gtest_test_utils.Subprocess( - [sys.executable, '-c', 'import os; print \'EMPTY_VAR\' in os.environ']) - CAN_PASS_EMPTY_ENV = eval(child.output) - - -# Check if this platform can unset environment variables in child processes. -# We set an env variable to a non-empty string, unset it, and invoke -# a python script in a subprocess to print whether the variable -# is NO LONGER in os.environ. -# We use 'eval' to parse the child's output so that an exception -# is thrown if the input is neither 'True' nor 'False'. -CAN_UNSET_ENV = False -if sys.executable: - os.environ['UNSET_VAR'] = 'X' - del os.environ['UNSET_VAR'] - child = gtest_test_utils.Subprocess( - [sys.executable, '-c', 'import os; print \'UNSET_VAR\' not in os.environ' - ]) - CAN_UNSET_ENV = eval(child.output) - - -# Checks if we should test with an empty filter. This doesn't -# make sense on platforms that cannot pass empty env variables (Win32) -# and on platforms that cannot unset variables (since we cannot tell -# the difference between "" and NULL -- Borland and Solaris < 5.10) -CAN_TEST_EMPTY_FILTER = (CAN_PASS_EMPTY_ENV and CAN_UNSET_ENV) - - -# The environment variable for specifying the test filters. -FILTER_ENV_VAR = 'GTEST_FILTER' - -# The environment variables for test sharding. -TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS' -SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX' -SHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE' - -# The command line flag for specifying the test filters. -FILTER_FLAG = 'gtest_filter' - -# The command line flag for including disabled tests. -ALSO_RUN_DISABLED_TESTS_FLAG = 'gtest_also_run_disabled_tests' - -# Command to run the gtest_filter_unittest_ program. -COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_filter_unittest_') - -# Regex for determining whether parameterized tests are enabled in the binary. -PARAM_TEST_REGEX = re.compile(r'/ParamTest') - -# Regex for parsing test case names from Google Test's output. -TEST_CASE_REGEX = re.compile(r'^\[\-+\] \d+ tests? from (\w+(/\w+)?)') - -# Regex for parsing test names from Google Test's output. -TEST_REGEX = re.compile(r'^\[\s*RUN\s*\].*\.(\w+(/\w+)?)') - -# The command line flag to tell Google Test to output the list of tests it -# will run. -LIST_TESTS_FLAG = '--gtest_list_tests' - -# Indicates whether Google Test supports death tests. -SUPPORTS_DEATH_TESTS = 'HasDeathTest' in gtest_test_utils.Subprocess( - [COMMAND, LIST_TESTS_FLAG]).output - -# Full names of all tests in gtest_filter_unittests_. -PARAM_TESTS = [ - 'SeqP/ParamTest.TestX/0', - 'SeqP/ParamTest.TestX/1', - 'SeqP/ParamTest.TestY/0', - 'SeqP/ParamTest.TestY/1', - 'SeqQ/ParamTest.TestX/0', - 'SeqQ/ParamTest.TestX/1', - 'SeqQ/ParamTest.TestY/0', - 'SeqQ/ParamTest.TestY/1', - ] - -DISABLED_TESTS = [ - 'BarTest.DISABLED_TestFour', - 'BarTest.DISABLED_TestFive', - 'BazTest.DISABLED_TestC', - 'DISABLED_FoobarTest.Test1', - 'DISABLED_FoobarTest.DISABLED_Test2', - 'DISABLED_FoobarbazTest.TestA', - ] - -if SUPPORTS_DEATH_TESTS: - DEATH_TESTS = [ - 'HasDeathTest.Test1', - 'HasDeathTest.Test2', - ] -else: - DEATH_TESTS = [] - -# All the non-disabled tests. -ACTIVE_TESTS = [ - 'FooTest.Abc', - 'FooTest.Xyz', - - 'BarTest.TestOne', - 'BarTest.TestTwo', - 'BarTest.TestThree', - - 'BazTest.TestOne', - 'BazTest.TestA', - 'BazTest.TestB', - ] + DEATH_TESTS + PARAM_TESTS - -param_tests_present = None - -# Utilities. - -environ = os.environ.copy() - - -def SetEnvVar(env_var, value): - """Sets the env variable to 'value'; unsets it when 'value' is None.""" - - if value is not None: - environ[env_var] = value - elif env_var in environ: - del environ[env_var] - - -def RunAndReturnOutput(args = None): - """Runs the test program and returns its output.""" - - return gtest_test_utils.Subprocess([COMMAND] + (args or []), - env=environ).output - - -def RunAndExtractTestList(args = None): - """Runs the test program and returns its exit code and a list of tests run.""" - - p = gtest_test_utils.Subprocess([COMMAND] + (args or []), env=environ) - tests_run = [] - test_case = '' - test = '' - for line in p.output.split('\n'): - match = TEST_CASE_REGEX.match(line) - if match is not None: - test_case = match.group(1) - else: - match = TEST_REGEX.match(line) - if match is not None: - test = match.group(1) - tests_run.append(test_case + '.' + test) - return (tests_run, p.exit_code) - - -def InvokeWithModifiedEnv(extra_env, function, *args, **kwargs): - """Runs the given function and arguments in a modified environment.""" - try: - original_env = environ.copy() - environ.update(extra_env) - return function(*args, **kwargs) - finally: - environ.clear() - environ.update(original_env) - - -def RunWithSharding(total_shards, shard_index, command): - """Runs a test program shard and returns exit code and a list of tests run.""" - - extra_env = {SHARD_INDEX_ENV_VAR: str(shard_index), - TOTAL_SHARDS_ENV_VAR: str(total_shards)} - return InvokeWithModifiedEnv(extra_env, RunAndExtractTestList, command) - -# The unit test. - - -class GTestFilterUnitTest(gtest_test_utils.TestCase): - """Tests the env variable or the command line flag to filter tests.""" - - # Utilities. - - def AssertSetEqual(self, lhs, rhs): - """Asserts that two sets are equal.""" - - for elem in lhs: - self.assert_(elem in rhs, '%s in %s' % (elem, rhs)) - - for elem in rhs: - self.assert_(elem in lhs, '%s in %s' % (elem, lhs)) - - def AssertPartitionIsValid(self, set_var, list_of_sets): - """Asserts that list_of_sets is a valid partition of set_var.""" - - full_partition = [] - for slice_var in list_of_sets: - full_partition.extend(slice_var) - self.assertEqual(len(set_var), len(full_partition)) - self.assertEqual(sets.Set(set_var), sets.Set(full_partition)) - - def AdjustForParameterizedTests(self, tests_to_run): - """Adjust tests_to_run in case value parameterized tests are disabled.""" - - global param_tests_present - if not param_tests_present: - return list(sets.Set(tests_to_run) - sets.Set(PARAM_TESTS)) - else: - return tests_to_run - - def RunAndVerify(self, gtest_filter, tests_to_run): - """Checks that the binary runs correct set of tests for a given filter.""" - - tests_to_run = self.AdjustForParameterizedTests(tests_to_run) - - # First, tests using the environment variable. - - # Windows removes empty variables from the environment when passing it - # to a new process. This means it is impossible to pass an empty filter - # into a process using the environment variable. However, we can still - # test the case when the variable is not supplied (i.e., gtest_filter is - # None). - # pylint: disable-msg=C6403 - if CAN_TEST_EMPTY_FILTER or gtest_filter != '': - SetEnvVar(FILTER_ENV_VAR, gtest_filter) - tests_run = RunAndExtractTestList()[0] - SetEnvVar(FILTER_ENV_VAR, None) - self.AssertSetEqual(tests_run, tests_to_run) - # pylint: enable-msg=C6403 - - # Next, tests using the command line flag. - - if gtest_filter is None: - args = [] - else: - args = ['--%s=%s' % (FILTER_FLAG, gtest_filter)] - - tests_run = RunAndExtractTestList(args)[0] - self.AssertSetEqual(tests_run, tests_to_run) - - def RunAndVerifyWithSharding(self, gtest_filter, total_shards, tests_to_run, - args=None, check_exit_0=False): - """Checks that binary runs correct tests for the given filter and shard. - - Runs all shards of gtest_filter_unittest_ with the given filter, and - verifies that the right set of tests were run. The union of tests run - on each shard should be identical to tests_to_run, without duplicates. - If check_exit_0, . - - Args: - gtest_filter: A filter to apply to the tests. - total_shards: A total number of shards to split test run into. - tests_to_run: A set of tests expected to run. - args : Arguments to pass to the to the test binary. - check_exit_0: When set to a true value, make sure that all shards - return 0. - """ - - tests_to_run = self.AdjustForParameterizedTests(tests_to_run) - - # Windows removes empty variables from the environment when passing it - # to a new process. This means it is impossible to pass an empty filter - # into a process using the environment variable. However, we can still - # test the case when the variable is not supplied (i.e., gtest_filter is - # None). - # pylint: disable-msg=C6403 - if CAN_TEST_EMPTY_FILTER or gtest_filter != '': - SetEnvVar(FILTER_ENV_VAR, gtest_filter) - partition = [] - for i in range(0, total_shards): - (tests_run, exit_code) = RunWithSharding(total_shards, i, args) - if check_exit_0: - self.assertEqual(0, exit_code) - partition.append(tests_run) - - self.AssertPartitionIsValid(tests_to_run, partition) - SetEnvVar(FILTER_ENV_VAR, None) - # pylint: enable-msg=C6403 - - def RunAndVerifyAllowingDisabled(self, gtest_filter, tests_to_run): - """Checks that the binary runs correct set of tests for the given filter. - - Runs gtest_filter_unittest_ with the given filter, and enables - disabled tests. Verifies that the right set of tests were run. - - Args: - gtest_filter: A filter to apply to the tests. - tests_to_run: A set of tests expected to run. - """ - - tests_to_run = self.AdjustForParameterizedTests(tests_to_run) - - # Construct the command line. - args = ['--%s' % ALSO_RUN_DISABLED_TESTS_FLAG] - if gtest_filter is not None: - args.append('--%s=%s' % (FILTER_FLAG, gtest_filter)) - - tests_run = RunAndExtractTestList(args)[0] - self.AssertSetEqual(tests_run, tests_to_run) - - def setUp(self): - """Sets up test case. - - Determines whether value-parameterized tests are enabled in the binary and - sets the flags accordingly. - """ - - global param_tests_present - if param_tests_present is None: - param_tests_present = PARAM_TEST_REGEX.search( - RunAndReturnOutput()) is not None - - def testDefaultBehavior(self): - """Tests the behavior of not specifying the filter.""" - - self.RunAndVerify(None, ACTIVE_TESTS) - - def testDefaultBehaviorWithShards(self): - """Tests the behavior without the filter, with sharding enabled.""" - - self.RunAndVerifyWithSharding(None, 1, ACTIVE_TESTS) - self.RunAndVerifyWithSharding(None, 2, ACTIVE_TESTS) - self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS) - 1, ACTIVE_TESTS) - self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS), ACTIVE_TESTS) - self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS) + 1, ACTIVE_TESTS) - - def testEmptyFilter(self): - """Tests an empty filter.""" - - self.RunAndVerify('', []) - self.RunAndVerifyWithSharding('', 1, []) - self.RunAndVerifyWithSharding('', 2, []) - - def testBadFilter(self): - """Tests a filter that matches nothing.""" - - self.RunAndVerify('BadFilter', []) - self.RunAndVerifyAllowingDisabled('BadFilter', []) - - def testFullName(self): - """Tests filtering by full name.""" - - self.RunAndVerify('FooTest.Xyz', ['FooTest.Xyz']) - self.RunAndVerifyAllowingDisabled('FooTest.Xyz', ['FooTest.Xyz']) - self.RunAndVerifyWithSharding('FooTest.Xyz', 5, ['FooTest.Xyz']) - - def testUniversalFilters(self): - """Tests filters that match everything.""" - - self.RunAndVerify('*', ACTIVE_TESTS) - self.RunAndVerify('*.*', ACTIVE_TESTS) - self.RunAndVerifyWithSharding('*.*', len(ACTIVE_TESTS) - 3, ACTIVE_TESTS) - self.RunAndVerifyAllowingDisabled('*', ACTIVE_TESTS + DISABLED_TESTS) - self.RunAndVerifyAllowingDisabled('*.*', ACTIVE_TESTS + DISABLED_TESTS) - - def testFilterByTestCase(self): - """Tests filtering by test case name.""" - - self.RunAndVerify('FooTest.*', ['FooTest.Abc', 'FooTest.Xyz']) - - BAZ_TESTS = ['BazTest.TestOne', 'BazTest.TestA', 'BazTest.TestB'] - self.RunAndVerify('BazTest.*', BAZ_TESTS) - self.RunAndVerifyAllowingDisabled('BazTest.*', - BAZ_TESTS + ['BazTest.DISABLED_TestC']) - - def testFilterByTest(self): - """Tests filtering by test name.""" - - self.RunAndVerify('*.TestOne', ['BarTest.TestOne', 'BazTest.TestOne']) - - def testFilterDisabledTests(self): - """Select only the disabled tests to run.""" - - self.RunAndVerify('DISABLED_FoobarTest.Test1', []) - self.RunAndVerifyAllowingDisabled('DISABLED_FoobarTest.Test1', - ['DISABLED_FoobarTest.Test1']) - - self.RunAndVerify('*DISABLED_*', []) - self.RunAndVerifyAllowingDisabled('*DISABLED_*', DISABLED_TESTS) - - self.RunAndVerify('*.DISABLED_*', []) - self.RunAndVerifyAllowingDisabled('*.DISABLED_*', [ - 'BarTest.DISABLED_TestFour', - 'BarTest.DISABLED_TestFive', - 'BazTest.DISABLED_TestC', - 'DISABLED_FoobarTest.DISABLED_Test2', - ]) - - self.RunAndVerify('DISABLED_*', []) - self.RunAndVerifyAllowingDisabled('DISABLED_*', [ - 'DISABLED_FoobarTest.Test1', - 'DISABLED_FoobarTest.DISABLED_Test2', - 'DISABLED_FoobarbazTest.TestA', - ]) - - def testWildcardInTestCaseName(self): - """Tests using wildcard in the test case name.""" - - self.RunAndVerify('*a*.*', [ - 'BarTest.TestOne', - 'BarTest.TestTwo', - 'BarTest.TestThree', - - 'BazTest.TestOne', - 'BazTest.TestA', - 'BazTest.TestB', ] + DEATH_TESTS + PARAM_TESTS) - - def testWildcardInTestName(self): - """Tests using wildcard in the test name.""" - - self.RunAndVerify('*.*A*', ['FooTest.Abc', 'BazTest.TestA']) - - def testFilterWithoutDot(self): - """Tests a filter that has no '.' in it.""" - - self.RunAndVerify('*z*', [ - 'FooTest.Xyz', - - 'BazTest.TestOne', - 'BazTest.TestA', - 'BazTest.TestB', - ]) - - def testTwoPatterns(self): - """Tests filters that consist of two patterns.""" - - self.RunAndVerify('Foo*.*:*A*', [ - 'FooTest.Abc', - 'FooTest.Xyz', - - 'BazTest.TestA', - ]) - - # An empty pattern + a non-empty one - self.RunAndVerify(':*A*', ['FooTest.Abc', 'BazTest.TestA']) - - def testThreePatterns(self): - """Tests filters that consist of three patterns.""" - - self.RunAndVerify('*oo*:*A*:*One', [ - 'FooTest.Abc', - 'FooTest.Xyz', - - 'BarTest.TestOne', - - 'BazTest.TestOne', - 'BazTest.TestA', - ]) - - # The 2nd pattern is empty. - self.RunAndVerify('*oo*::*One', [ - 'FooTest.Abc', - 'FooTest.Xyz', - - 'BarTest.TestOne', - - 'BazTest.TestOne', - ]) - - # The last 2 patterns are empty. - self.RunAndVerify('*oo*::', [ - 'FooTest.Abc', - 'FooTest.Xyz', - ]) - - def testNegativeFilters(self): - self.RunAndVerify('*-BazTest.TestOne', [ - 'FooTest.Abc', - 'FooTest.Xyz', - - 'BarTest.TestOne', - 'BarTest.TestTwo', - 'BarTest.TestThree', - - 'BazTest.TestA', - 'BazTest.TestB', - ] + DEATH_TESTS + PARAM_TESTS) - - self.RunAndVerify('*-FooTest.Abc:BazTest.*', [ - 'FooTest.Xyz', - - 'BarTest.TestOne', - 'BarTest.TestTwo', - 'BarTest.TestThree', - ] + DEATH_TESTS + PARAM_TESTS) - - self.RunAndVerify('BarTest.*-BarTest.TestOne', [ - 'BarTest.TestTwo', - 'BarTest.TestThree', - ]) - - # Tests without leading '*'. - self.RunAndVerify('-FooTest.Abc:FooTest.Xyz:BazTest.*', [ - 'BarTest.TestOne', - 'BarTest.TestTwo', - 'BarTest.TestThree', - ] + DEATH_TESTS + PARAM_TESTS) - - # Value parameterized tests. - self.RunAndVerify('*/*', PARAM_TESTS) - - # Value parameterized tests filtering by the sequence name. - self.RunAndVerify('SeqP/*', [ - 'SeqP/ParamTest.TestX/0', - 'SeqP/ParamTest.TestX/1', - 'SeqP/ParamTest.TestY/0', - 'SeqP/ParamTest.TestY/1', - ]) - - # Value parameterized tests filtering by the test name. - self.RunAndVerify('*/0', [ - 'SeqP/ParamTest.TestX/0', - 'SeqP/ParamTest.TestY/0', - 'SeqQ/ParamTest.TestX/0', - 'SeqQ/ParamTest.TestY/0', - ]) - - def testFlagOverridesEnvVar(self): - """Tests that the filter flag overrides the filtering env. variable.""" - - SetEnvVar(FILTER_ENV_VAR, 'Foo*') - args = ['--%s=%s' % (FILTER_FLAG, '*One')] - tests_run = RunAndExtractTestList(args)[0] - SetEnvVar(FILTER_ENV_VAR, None) - - self.AssertSetEqual(tests_run, ['BarTest.TestOne', 'BazTest.TestOne']) - - def testShardStatusFileIsCreated(self): - """Tests that the shard file is created if specified in the environment.""" - - shard_status_file = os.path.join(gtest_test_utils.GetTempDir(), - 'shard_status_file') - self.assert_(not os.path.exists(shard_status_file)) - - extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file} - try: - InvokeWithModifiedEnv(extra_env, RunAndReturnOutput) - finally: - self.assert_(os.path.exists(shard_status_file)) - os.remove(shard_status_file) - - def testShardStatusFileIsCreatedWithListTests(self): - """Tests that the shard file is created with the "list_tests" flag.""" - - shard_status_file = os.path.join(gtest_test_utils.GetTempDir(), - 'shard_status_file2') - self.assert_(not os.path.exists(shard_status_file)) - - extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file} - try: - output = InvokeWithModifiedEnv(extra_env, - RunAndReturnOutput, - [LIST_TESTS_FLAG]) - finally: - # This assertion ensures that Google Test enumerated the tests as - # opposed to running them. - self.assert_('[==========]' not in output, - 'Unexpected output during test enumeration.\n' - 'Please ensure that LIST_TESTS_FLAG is assigned the\n' - 'correct flag value for listing Google Test tests.') - - self.assert_(os.path.exists(shard_status_file)) - os.remove(shard_status_file) - - if SUPPORTS_DEATH_TESTS: - def testShardingWorksWithDeathTests(self): - """Tests integration with death tests and sharding.""" - - gtest_filter = 'HasDeathTest.*:SeqP/*' - expected_tests = [ - 'HasDeathTest.Test1', - 'HasDeathTest.Test2', - - 'SeqP/ParamTest.TestX/0', - 'SeqP/ParamTest.TestX/1', - 'SeqP/ParamTest.TestY/0', - 'SeqP/ParamTest.TestY/1', - ] - - for flag in ['--gtest_death_test_style=threadsafe', - '--gtest_death_test_style=fast']: - self.RunAndVerifyWithSharding(gtest_filter, 3, expected_tests, - check_exit_0=True, args=[flag]) - self.RunAndVerifyWithSharding(gtest_filter, 5, expected_tests, - check_exit_0=True, args=[flag]) - -if __name__ == '__main__': - gtest_test_utils.Main() diff --git a/googletest/test/gtest_filter_unittest_.cc b/googletest/test/gtest_filter_unittest_.cc deleted file mode 100644 index e74a7a3..0000000 --- a/googletest/test/gtest_filter_unittest_.cc +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) - -// Unit test for Google Test test filters. -// -// A user can specify which test(s) in a Google Test program to run via -// either the GTEST_FILTER environment variable or the --gtest_filter -// flag. This is used for testing such functionality. -// -// The program will be invoked from a Python unit test. Don't run it -// directly. - -#include "gtest/gtest.h" - -namespace { - -// Test case FooTest. - -class FooTest : public testing::Test { -}; - -TEST_F(FooTest, Abc) { -} - -TEST_F(FooTest, Xyz) { - FAIL() << "Expected failure."; -} - -// Test case BarTest. - -TEST(BarTest, TestOne) { -} - -TEST(BarTest, TestTwo) { -} - -TEST(BarTest, TestThree) { -} - -TEST(BarTest, DISABLED_TestFour) { - FAIL() << "Expected failure."; -} - -TEST(BarTest, DISABLED_TestFive) { - FAIL() << "Expected failure."; -} - -// Test case BazTest. - -TEST(BazTest, TestOne) { - FAIL() << "Expected failure."; -} - -TEST(BazTest, TestA) { -} - -TEST(BazTest, TestB) { -} - -TEST(BazTest, DISABLED_TestC) { - FAIL() << "Expected failure."; -} - -// Test case HasDeathTest - -TEST(HasDeathTest, Test1) { - EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); -} - -// We need at least two death tests to make sure that the all death tests -// aren't on the first shard. -TEST(HasDeathTest, Test2) { - EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); -} - -// Test case FoobarTest - -TEST(DISABLED_FoobarTest, Test1) { - FAIL() << "Expected failure."; -} - -TEST(DISABLED_FoobarTest, DISABLED_Test2) { - FAIL() << "Expected failure."; -} - -// Test case FoobarbazTest - -TEST(DISABLED_FoobarbazTest, TestA) { - FAIL() << "Expected failure."; -} - -class ParamTest : public testing::TestWithParam { -}; - -TEST_P(ParamTest, TestX) { -} - -TEST_P(ParamTest, TestY) { -} - -INSTANTIATE_TEST_CASE_P(SeqP, ParamTest, testing::Values(1, 2)); -INSTANTIATE_TEST_CASE_P(SeqQ, ParamTest, testing::Values(5, 6)); - -} // namespace - -int main(int argc, char **argv) { - ::testing::InitGoogleTest(&argc, argv); - - return RUN_ALL_TESTS(); -} diff --git a/googletest/test/gtest_throw_on_failure_test.py b/googletest/test/gtest_throw_on_failure_test.py deleted file mode 100755 index 5678ffe..0000000 --- a/googletest/test/gtest_throw_on_failure_test.py +++ /dev/null @@ -1,171 +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 Google Test's throw-on-failure mode with exceptions disabled. - -This script invokes gtest_throw_on_failure_test_ (a program written with -Google Test) with different environments and command line flags. -""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import os -import gtest_test_utils - - -# Constants. - -# The command line flag for enabling/disabling the throw-on-failure mode. -THROW_ON_FAILURE = 'gtest_throw_on_failure' - -# Path to the gtest_throw_on_failure_test_ program, compiled with -# exceptions disabled. -EXE_PATH = gtest_test_utils.GetTestExecutablePath( - 'gtest_throw_on_failure_test_') - - -# Utilities. - - -def SetEnvVar(env_var, value): - """Sets an environment variable to a given value; unsets it when the - given value is None. - """ - - env_var = env_var.upper() - if value is not None: - os.environ[env_var] = value - elif env_var in os.environ: - del os.environ[env_var] - - -def Run(command): - """Runs a command; returns True/False if its exit code is/isn't 0.""" - - print 'Running "%s". . .' % ' '.join(command) - p = gtest_test_utils.Subprocess(command) - return p.exited and p.exit_code == 0 - - -# The tests. TODO(wan@google.com): refactor the class to share common -# logic with code in gtest_break_on_failure_unittest.py. -class ThrowOnFailureTest(gtest_test_utils.TestCase): - """Tests the throw-on-failure mode.""" - - def RunAndVerify(self, env_var_value, flag_value, should_fail): - """Runs gtest_throw_on_failure_test_ and verifies that it does - (or does not) exit with a non-zero code. - - Args: - env_var_value: value of the GTEST_BREAK_ON_FAILURE environment - variable; None if the variable should be unset. - flag_value: value of the --gtest_break_on_failure flag; - None if the flag should not be present. - should_fail: True iff the program is expected to fail. - """ - - SetEnvVar(THROW_ON_FAILURE, env_var_value) - - if env_var_value is None: - env_var_value_msg = ' is not set' - else: - env_var_value_msg = '=' + env_var_value - - if flag_value is None: - flag = '' - elif flag_value == '0': - flag = '--%s=0' % THROW_ON_FAILURE - else: - flag = '--%s' % THROW_ON_FAILURE - - command = [EXE_PATH] - if flag: - command.append(flag) - - if should_fail: - should_or_not = 'should' - else: - should_or_not = 'should not' - - failed = not Run(command) - - SetEnvVar(THROW_ON_FAILURE, None) - - msg = ('when %s%s, an assertion failure in "%s" %s cause a non-zero ' - 'exit code.' % - (THROW_ON_FAILURE, env_var_value_msg, ' '.join(command), - should_or_not)) - self.assert_(failed == should_fail, msg) - - def testDefaultBehavior(self): - """Tests the behavior of the default mode.""" - - self.RunAndVerify(env_var_value=None, flag_value=None, should_fail=False) - - def testThrowOnFailureEnvVar(self): - """Tests using the GTEST_THROW_ON_FAILURE environment variable.""" - - self.RunAndVerify(env_var_value='0', - flag_value=None, - should_fail=False) - self.RunAndVerify(env_var_value='1', - flag_value=None, - should_fail=True) - - def testThrowOnFailureFlag(self): - """Tests using the --gtest_throw_on_failure flag.""" - - self.RunAndVerify(env_var_value=None, - flag_value='0', - should_fail=False) - self.RunAndVerify(env_var_value=None, - flag_value='1', - should_fail=True) - - def testThrowOnFailureFlagOverridesEnvVar(self): - """Tests that --gtest_throw_on_failure overrides GTEST_THROW_ON_FAILURE.""" - - self.RunAndVerify(env_var_value='0', - flag_value='0', - should_fail=False) - self.RunAndVerify(env_var_value='0', - flag_value='1', - should_fail=True) - self.RunAndVerify(env_var_value='1', - flag_value='0', - should_fail=False) - self.RunAndVerify(env_var_value='1', - flag_value='1', - should_fail=True) - - -if __name__ == '__main__': - gtest_test_utils.Main() diff --git a/googletest/test/gtest_throw_on_failure_test_.cc b/googletest/test/gtest_throw_on_failure_test_.cc deleted file mode 100644 index 2b88fe3..0000000 --- a/googletest/test/gtest_throw_on_failure_test_.cc +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2009, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) - -// Tests Google Test's throw-on-failure mode with exceptions disabled. -// -// This program must be compiled with exceptions disabled. It will be -// 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 // for fflush, fprintf, NULL, etc. -#include // for exit -#include // for set_terminate - -// 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(1); -} - -int main(int argc, char** argv) { -#if GTEST_HAS_EXCEPTIONS - std::set_terminate(&TerminateHandler); -#endif - testing::InitGoogleTest(&argc, argv); - - // We want to ensure that people can use Google Test assertions in - // other testing frameworks, as long as they initialize Google Test - // properly and set the throw-on-failure mode. Therefore, we don't - // use Google Test's constructs for defining and running tests - // (e.g. TEST and RUN_ALL_TESTS) here. - - // In the throw-on-failure mode with exceptions disabled, this - // assertion will cause the program to exit with a non-zero code. - EXPECT_EQ(2, 3); - - // When not in the throw-on-failure mode, the control will reach - // here. - return 0; -} -- cgit v0.12 From 35aa4fe9245590721146af854789913c04c2c7fb Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 13:32:07 -0400 Subject: gtest catch exceptions test and gtest shuffle test --- googletest/test/BUILD.bazel | 36 +-- .../test/googletest-catch-exceptions-test.py | 235 +++++++++++++++ .../test/googletest-catch-exceptions-test_.cc | 311 ++++++++++++++++++++ googletest/test/googletest-listener-test.cc | 311 ++++++++++++++++++++ googletest/test/googletest-shuffle-test.py | 325 +++++++++++++++++++++ googletest/test/googletest-shuffle-test_.cc | 103 +++++++ googletest/test/gtest_catch_exceptions_test.py | 235 --------------- googletest/test/gtest_catch_exceptions_test_.cc | 311 -------------------- googletest/test/gtest_shuffle_test.py | 325 --------------------- googletest/test/gtest_shuffle_test_.cc | 103 ------- 10 files changed, 1301 insertions(+), 994 deletions(-) create mode 100755 googletest/test/googletest-catch-exceptions-test.py create mode 100644 googletest/test/googletest-catch-exceptions-test_.cc create mode 100644 googletest/test/googletest-listener-test.cc create mode 100755 googletest/test/googletest-shuffle-test.py create mode 100644 googletest/test/googletest-shuffle-test_.cc delete mode 100755 googletest/test/gtest_catch_exceptions_test.py delete mode 100644 googletest/test/gtest_catch_exceptions_test_.cc delete mode 100755 googletest/test/gtest_shuffle_test.py delete mode 100644 googletest/test/gtest_shuffle_test_.cc diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 090c463..319c849 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -107,14 +107,10 @@ cc_test( #These googletest tests have their own main() cc_test( - name = "gtest-listener_test", + name = "googletest-listener-test", size = "small", - srcs = [ - "gtest-listener_test.cc", - ], - deps = [ - "//:gtest", - ], + srcs = ["googletest-listener-test.cc"], + deps = ["//:gtest_main"], ) cc_test( @@ -301,41 +297,41 @@ py_test( ) cc_binary( - name = "gtest_shuffle_test_", - srcs = ["gtest_shuffle_test_.cc"], + name = "googletest-shuffle-test_", + srcs = ["googletest-shuffle-test_.cc"], deps = ["//:gtest"], ) py_test( - name = "gtest_shuffle_test", + name = "googletest-shuffle-test", size = "small", - srcs = ["gtest_shuffle_test.py"], - data = [":gtest_shuffle_test_"], + srcs = ["googletest-shuffle-test.py"], + data = [":googletest-shuffle-test_"], deps = [":gtest_test_utils"], ) cc_binary( - name = "gtest_catch_exceptions_no_ex_test_", + name = "googletest_catch_exceptions_no_ex_test_", testonly = 1, - srcs = ["gtest_catch_exceptions_test_.cc"], + srcs = ["googletest-catch-exceptions-test_.cc"], deps = ["//:gtest_main"], ) cc_binary( - name = "gtest_catch_exceptions_ex_test_", + name = "googletest_catch_exceptions_ex_test_", testonly = 1, - srcs = ["gtest_catch_exceptions_test_.cc"], + srcs = ["googletest-catch-exceptions-test_.cc"], copts = ["-fexceptions"], deps = ["//:gtest_main"], ) py_test( - name = "gtest_catch_exceptions_test", + name = "googletest-catch-exceptions-test", size = "small", - srcs = ["gtest_catch_exceptions_test.py"], + srcs = ["googletest-catch-exceptions-test.py"], data = [ - ":gtest_catch_exceptions_ex_test_", - ":gtest_catch_exceptions_no_ex_test_", + ":googletest_catch_exceptions_ex_test_", + ":googletest_catch_exceptions_no_ex_test_", ], deps = [":gtest_test_utils"], ) diff --git a/googletest/test/googletest-catch-exceptions-test.py b/googletest/test/googletest-catch-exceptions-test.py new file mode 100755 index 0000000..d12a32a --- /dev/null +++ b/googletest/test/googletest-catch-exceptions-test.py @@ -0,0 +1,235 @@ +#!/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 gtest_test_utils + +# Constants. +FLAG_PREFIX = '--gtest_' +LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests' +NO_CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions=0' +FILTER_FLAG = FLAG_PREFIX + 'filter' + +# Path to the gtest_catch_exceptions_ex_test_ binary, compiled with +# exceptions enabled. +EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath( + 'googletest_catch_exceptions_ex_test_') + +# Path to the gtest_catch_exceptions_test_ binary, compiled with +# exceptions disabled. +EXE_PATH = gtest_test_utils.GetTestExecutablePath( + 'googletest_catch_exceptions_no_ex_test_') + +environ = gtest_test_utils.environ +SetEnvVar = gtest_test_utils.SetEnvVar + +# Tests in this file run a Google-Test-based test program and expect it +# to terminate prematurely. Therefore they are incompatible with +# the premature-exit-file protocol by design. Unset the +# premature-exit filepath to prevent Google Test from creating +# the file. +SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None) + +TEST_LIST = gtest_test_utils.Subprocess( + [EXE_PATH, LIST_TESTS_FLAG], env=environ).output + +SUPPORTS_SEH_EXCEPTIONS = 'ThrowsSehException' in TEST_LIST + +if SUPPORTS_SEH_EXCEPTIONS: + BINARY_OUTPUT = gtest_test_utils.Subprocess([EXE_PATH], env=environ).output + +EX_BINARY_OUTPUT = gtest_test_utils.Subprocess( + [EX_EXE_PATH], env=environ).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"') + + if ('CxxExceptionInDestructorTest.ThrowsExceptionInDestructor' in + EX_BINARY_OUTPUT): + + 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, + NO_CATCH_EXCEPTIONS_FLAG, + FITLER_OUT_SEH_TESTS_FLAG], + env=environ).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/googletest/test/googletest-catch-exceptions-test_.cc b/googletest/test/googletest-catch-exceptions-test_.cc new file mode 100644 index 0000000..c6d953c --- /dev/null +++ b/googletest/test/googletest-catch-exceptions-test_.cc @@ -0,0 +1,311 @@ +// 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 // NOLINT +#include // For exit(). + +#if GTEST_HAS_SEH +# include +#endif + +#if GTEST_HAS_EXCEPTIONS +# include // For set_terminate(). +# include +#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."; +} + +// Exceptions in destructors are not supported in C++11. +#if !GTEST_LANG_CXX11 +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) {} +#endif // C++11 mode + +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/googletest/test/googletest-listener-test.cc b/googletest/test/googletest-listener-test.cc new file mode 100644 index 0000000..639529c --- /dev/null +++ b/googletest/test/googletest-listener-test.cc @@ -0,0 +1,311 @@ +// Copyright 2009 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vladl@google.com (Vlad Losev) +// +// The Google C++ Testing and Mocking Framework (Google Test) +// +// This file verifies Google Test event listeners receive events at the +// right times. + +#include "gtest/gtest.h" +#include + +using ::testing::AddGlobalTestEnvironment; +using ::testing::Environment; +using ::testing::InitGoogleTest; +using ::testing::Test; +using ::testing::TestCase; +using ::testing::TestEventListener; +using ::testing::TestInfo; +using ::testing::TestPartResult; +using ::testing::UnitTest; + +// Used by tests to register their events. +std::vector* g_events = NULL; + +namespace testing { +namespace internal { + +class EventRecordingListener : public TestEventListener { + public: + explicit EventRecordingListener(const char* name) : name_(name) {} + + protected: + virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) { + g_events->push_back(GetFullMethodName("OnTestProgramStart")); + } + + virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, + int iteration) { + Message message; + message << GetFullMethodName("OnTestIterationStart") + << "(" << iteration << ")"; + g_events->push_back(message.GetString()); + } + + virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) { + g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpStart")); + } + + virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) { + g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpEnd")); + } + + virtual void OnTestCaseStart(const TestCase& /*test_case*/) { + g_events->push_back(GetFullMethodName("OnTestCaseStart")); + } + + virtual void OnTestStart(const TestInfo& /*test_info*/) { + g_events->push_back(GetFullMethodName("OnTestStart")); + } + + virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) { + g_events->push_back(GetFullMethodName("OnTestPartResult")); + } + + virtual void OnTestEnd(const TestInfo& /*test_info*/) { + g_events->push_back(GetFullMethodName("OnTestEnd")); + } + + virtual void OnTestCaseEnd(const TestCase& /*test_case*/) { + g_events->push_back(GetFullMethodName("OnTestCaseEnd")); + } + + virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) { + g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownStart")); + } + + virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) { + g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownEnd")); + } + + virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, + int iteration) { + Message message; + message << GetFullMethodName("OnTestIterationEnd") + << "(" << iteration << ")"; + g_events->push_back(message.GetString()); + } + + virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) { + g_events->push_back(GetFullMethodName("OnTestProgramEnd")); + } + + private: + std::string GetFullMethodName(const char* name) { + return name_ + "." + name; + } + + std::string name_; +}; + +class EnvironmentInvocationCatcher : public Environment { + protected: + virtual void SetUp() { + g_events->push_back("Environment::SetUp"); + } + + virtual void TearDown() { + g_events->push_back("Environment::TearDown"); + } +}; + +class ListenerTest : public Test { + protected: + static void SetUpTestCase() { + g_events->push_back("ListenerTest::SetUpTestCase"); + } + + static void TearDownTestCase() { + g_events->push_back("ListenerTest::TearDownTestCase"); + } + + virtual void SetUp() { + g_events->push_back("ListenerTest::SetUp"); + } + + virtual void TearDown() { + g_events->push_back("ListenerTest::TearDown"); + } +}; + +TEST_F(ListenerTest, DoesFoo) { + // Test execution order within a test case is not guaranteed so we are not + // recording the test name. + g_events->push_back("ListenerTest::* Test Body"); + SUCCEED(); // Triggers OnTestPartResult. +} + +TEST_F(ListenerTest, DoesBar) { + g_events->push_back("ListenerTest::* Test Body"); + SUCCEED(); // Triggers OnTestPartResult. +} + +} // namespace internal + +} // namespace testing + +using ::testing::internal::EnvironmentInvocationCatcher; +using ::testing::internal::EventRecordingListener; + +void VerifyResults(const std::vector& data, + const char* const* expected_data, + size_t expected_data_size) { + const size_t actual_size = data.size(); + // If the following assertion fails, a new entry will be appended to + // data. Hence we save data.size() first. + EXPECT_EQ(expected_data_size, actual_size); + + // Compares the common prefix. + const size_t shorter_size = expected_data_size <= actual_size ? + expected_data_size : actual_size; + size_t i = 0; + for (; i < shorter_size; ++i) { + ASSERT_STREQ(expected_data[i], data[i].c_str()) + << "at position " << i; + } + + // Prints extra elements in the actual data. + for (; i < actual_size; ++i) { + printf(" Actual event #%lu: %s\n", + static_cast(i), data[i].c_str()); + } +} + +int main(int argc, char **argv) { + std::vector events; + g_events = &events; + InitGoogleTest(&argc, argv); + + UnitTest::GetInstance()->listeners().Append( + new EventRecordingListener("1st")); + UnitTest::GetInstance()->listeners().Append( + new EventRecordingListener("2nd")); + + AddGlobalTestEnvironment(new EnvironmentInvocationCatcher); + + GTEST_CHECK_(events.size() == 0) + << "AddGlobalTestEnvironment should not generate any events itself."; + + ::testing::GTEST_FLAG(repeat) = 2; + int ret_val = RUN_ALL_TESTS(); + + const char* const expected_events[] = { + "1st.OnTestProgramStart", + "2nd.OnTestProgramStart", + "1st.OnTestIterationStart(0)", + "2nd.OnTestIterationStart(0)", + "1st.OnEnvironmentsSetUpStart", + "2nd.OnEnvironmentsSetUpStart", + "Environment::SetUp", + "2nd.OnEnvironmentsSetUpEnd", + "1st.OnEnvironmentsSetUpEnd", + "1st.OnTestCaseStart", + "2nd.OnTestCaseStart", + "ListenerTest::SetUpTestCase", + "1st.OnTestStart", + "2nd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "ListenerTest::TearDown", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "1st.OnTestStart", + "2nd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "ListenerTest::TearDown", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "ListenerTest::TearDownTestCase", + "2nd.OnTestCaseEnd", + "1st.OnTestCaseEnd", + "1st.OnEnvironmentsTearDownStart", + "2nd.OnEnvironmentsTearDownStart", + "Environment::TearDown", + "2nd.OnEnvironmentsTearDownEnd", + "1st.OnEnvironmentsTearDownEnd", + "2nd.OnTestIterationEnd(0)", + "1st.OnTestIterationEnd(0)", + "1st.OnTestIterationStart(1)", + "2nd.OnTestIterationStart(1)", + "1st.OnEnvironmentsSetUpStart", + "2nd.OnEnvironmentsSetUpStart", + "Environment::SetUp", + "2nd.OnEnvironmentsSetUpEnd", + "1st.OnEnvironmentsSetUpEnd", + "1st.OnTestCaseStart", + "2nd.OnTestCaseStart", + "ListenerTest::SetUpTestCase", + "1st.OnTestStart", + "2nd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "ListenerTest::TearDown", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "1st.OnTestStart", + "2nd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "ListenerTest::TearDown", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "ListenerTest::TearDownTestCase", + "2nd.OnTestCaseEnd", + "1st.OnTestCaseEnd", + "1st.OnEnvironmentsTearDownStart", + "2nd.OnEnvironmentsTearDownStart", + "Environment::TearDown", + "2nd.OnEnvironmentsTearDownEnd", + "1st.OnEnvironmentsTearDownEnd", + "2nd.OnTestIterationEnd(1)", + "1st.OnTestIterationEnd(1)", + "2nd.OnTestProgramEnd", + "1st.OnTestProgramEnd" + }; + VerifyResults(events, + expected_events, + sizeof(expected_events)/sizeof(expected_events[0])); + + // We need to check manually for ad hoc test failures that happen after + // RUN_ALL_TESTS finishes. + if (UnitTest::GetInstance()->Failed()) + ret_val = 1; + + return ret_val; +} diff --git a/googletest/test/googletest-shuffle-test.py b/googletest/test/googletest-shuffle-test.py new file mode 100755 index 0000000..5ae9655 --- /dev/null +++ b/googletest/test/googletest-shuffle-test.py @@ -0,0 +1,325 @@ +#!/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. + +"""Verifies that test shuffling works.""" + +__author__ = 'wan@google.com (Zhanyong Wan)' + +import os +import gtest_test_utils + +# Command to run the googletest-shuffle-test_ program. +COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-shuffle-test_') + +# The environment variables for test sharding. +TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS' +SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX' + +TEST_FILTER = 'A*.A:A*.B:C*' + +ALL_TESTS = [] +ACTIVE_TESTS = [] +FILTERED_TESTS = [] +SHARDED_TESTS = [] + +SHUFFLED_ALL_TESTS = [] +SHUFFLED_ACTIVE_TESTS = [] +SHUFFLED_FILTERED_TESTS = [] +SHUFFLED_SHARDED_TESTS = [] + + +def AlsoRunDisabledTestsFlag(): + return '--gtest_also_run_disabled_tests' + + +def FilterFlag(test_filter): + return '--gtest_filter=%s' % (test_filter,) + + +def RepeatFlag(n): + return '--gtest_repeat=%s' % (n,) + + +def ShuffleFlag(): + return '--gtest_shuffle' + + +def RandomSeedFlag(n): + return '--gtest_random_seed=%s' % (n,) + + +def RunAndReturnOutput(extra_env, args): + """Runs the test program and returns its output.""" + + environ_copy = os.environ.copy() + environ_copy.update(extra_env) + + return gtest_test_utils.Subprocess([COMMAND] + args, env=environ_copy).output + + +def GetTestsForAllIterations(extra_env, args): + """Runs the test program and returns a list of test lists. + + Args: + extra_env: a map from environment variables to their values + args: command line flags to pass to googletest-shuffle-test_ + + Returns: + A list where the i-th element is the list of tests run in the i-th + test iteration. + """ + + test_iterations = [] + for line in RunAndReturnOutput(extra_env, args).split('\n'): + if line.startswith('----'): + tests = [] + test_iterations.append(tests) + elif line.strip(): + tests.append(line.strip()) # 'TestCaseName.TestName' + + return test_iterations + + +def GetTestCases(tests): + """Returns a list of test cases in the given full test names. + + Args: + tests: a list of full test names + + Returns: + A list of test cases from 'tests', in their original order. + Consecutive duplicates are removed. + """ + + test_cases = [] + for test in tests: + test_case = test.split('.')[0] + if not test_case in test_cases: + test_cases.append(test_case) + + return test_cases + + +def CalculateTestLists(): + """Calculates the list of tests run under different flags.""" + + if not ALL_TESTS: + ALL_TESTS.extend( + GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0]) + + if not ACTIVE_TESTS: + ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [])[0]) + + if not FILTERED_TESTS: + FILTERED_TESTS.extend( + GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0]) + + if not SHARDED_TESTS: + SHARDED_TESTS.extend( + GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', + SHARD_INDEX_ENV_VAR: '1'}, + [])[0]) + + if not SHUFFLED_ALL_TESTS: + SHUFFLED_ALL_TESTS.extend(GetTestsForAllIterations( + {}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)])[0]) + + if not SHUFFLED_ACTIVE_TESTS: + SHUFFLED_ACTIVE_TESTS.extend(GetTestsForAllIterations( + {}, [ShuffleFlag(), RandomSeedFlag(1)])[0]) + + if not SHUFFLED_FILTERED_TESTS: + SHUFFLED_FILTERED_TESTS.extend(GetTestsForAllIterations( + {}, [ShuffleFlag(), RandomSeedFlag(1), FilterFlag(TEST_FILTER)])[0]) + + if not SHUFFLED_SHARDED_TESTS: + SHUFFLED_SHARDED_TESTS.extend( + GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', + SHARD_INDEX_ENV_VAR: '1'}, + [ShuffleFlag(), RandomSeedFlag(1)])[0]) + + +class GTestShuffleUnitTest(gtest_test_utils.TestCase): + """Tests test shuffling.""" + + def setUp(self): + CalculateTestLists() + + def testShufflePreservesNumberOfTests(self): + self.assertEqual(len(ALL_TESTS), len(SHUFFLED_ALL_TESTS)) + self.assertEqual(len(ACTIVE_TESTS), len(SHUFFLED_ACTIVE_TESTS)) + self.assertEqual(len(FILTERED_TESTS), len(SHUFFLED_FILTERED_TESTS)) + self.assertEqual(len(SHARDED_TESTS), len(SHUFFLED_SHARDED_TESTS)) + + def testShuffleChangesTestOrder(self): + self.assert_(SHUFFLED_ALL_TESTS != ALL_TESTS, SHUFFLED_ALL_TESTS) + self.assert_(SHUFFLED_ACTIVE_TESTS != ACTIVE_TESTS, SHUFFLED_ACTIVE_TESTS) + self.assert_(SHUFFLED_FILTERED_TESTS != FILTERED_TESTS, + SHUFFLED_FILTERED_TESTS) + self.assert_(SHUFFLED_SHARDED_TESTS != SHARDED_TESTS, + SHUFFLED_SHARDED_TESTS) + + def testShuffleChangesTestCaseOrder(self): + self.assert_(GetTestCases(SHUFFLED_ALL_TESTS) != GetTestCases(ALL_TESTS), + GetTestCases(SHUFFLED_ALL_TESTS)) + self.assert_( + GetTestCases(SHUFFLED_ACTIVE_TESTS) != GetTestCases(ACTIVE_TESTS), + GetTestCases(SHUFFLED_ACTIVE_TESTS)) + self.assert_( + GetTestCases(SHUFFLED_FILTERED_TESTS) != GetTestCases(FILTERED_TESTS), + GetTestCases(SHUFFLED_FILTERED_TESTS)) + self.assert_( + GetTestCases(SHUFFLED_SHARDED_TESTS) != GetTestCases(SHARDED_TESTS), + GetTestCases(SHUFFLED_SHARDED_TESTS)) + + def testShuffleDoesNotRepeatTest(self): + for test in SHUFFLED_ALL_TESTS: + self.assertEqual(1, SHUFFLED_ALL_TESTS.count(test), + '%s appears more than once' % (test,)) + for test in SHUFFLED_ACTIVE_TESTS: + self.assertEqual(1, SHUFFLED_ACTIVE_TESTS.count(test), + '%s appears more than once' % (test,)) + for test in SHUFFLED_FILTERED_TESTS: + self.assertEqual(1, SHUFFLED_FILTERED_TESTS.count(test), + '%s appears more than once' % (test,)) + for test in SHUFFLED_SHARDED_TESTS: + self.assertEqual(1, SHUFFLED_SHARDED_TESTS.count(test), + '%s appears more than once' % (test,)) + + def testShuffleDoesNotCreateNewTest(self): + for test in SHUFFLED_ALL_TESTS: + self.assert_(test in ALL_TESTS, '%s is an invalid test' % (test,)) + for test in SHUFFLED_ACTIVE_TESTS: + self.assert_(test in ACTIVE_TESTS, '%s is an invalid test' % (test,)) + for test in SHUFFLED_FILTERED_TESTS: + self.assert_(test in FILTERED_TESTS, '%s is an invalid test' % (test,)) + for test in SHUFFLED_SHARDED_TESTS: + self.assert_(test in SHARDED_TESTS, '%s is an invalid test' % (test,)) + + def testShuffleIncludesAllTests(self): + for test in ALL_TESTS: + self.assert_(test in SHUFFLED_ALL_TESTS, '%s is missing' % (test,)) + for test in ACTIVE_TESTS: + self.assert_(test in SHUFFLED_ACTIVE_TESTS, '%s is missing' % (test,)) + for test in FILTERED_TESTS: + self.assert_(test in SHUFFLED_FILTERED_TESTS, '%s is missing' % (test,)) + for test in SHARDED_TESTS: + self.assert_(test in SHUFFLED_SHARDED_TESTS, '%s is missing' % (test,)) + + def testShuffleLeavesDeathTestsAtFront(self): + non_death_test_found = False + for test in SHUFFLED_ACTIVE_TESTS: + if 'DeathTest.' in test: + self.assert_(not non_death_test_found, + '%s appears after a non-death test' % (test,)) + else: + non_death_test_found = True + + def _VerifyTestCasesDoNotInterleave(self, tests): + test_cases = [] + for test in tests: + [test_case, _] = test.split('.') + if test_cases and test_cases[-1] != test_case: + test_cases.append(test_case) + self.assertEqual(1, test_cases.count(test_case), + 'Test case %s is not grouped together in %s' % + (test_case, tests)) + + def testShuffleDoesNotInterleaveTestCases(self): + self._VerifyTestCasesDoNotInterleave(SHUFFLED_ALL_TESTS) + self._VerifyTestCasesDoNotInterleave(SHUFFLED_ACTIVE_TESTS) + self._VerifyTestCasesDoNotInterleave(SHUFFLED_FILTERED_TESTS) + self._VerifyTestCasesDoNotInterleave(SHUFFLED_SHARDED_TESTS) + + def testShuffleRestoresOrderAfterEachIteration(self): + # Get the test lists in all 3 iterations, using random seed 1, 2, + # and 3 respectively. Google Test picks a different seed in each + # iteration, and this test depends on the current implementation + # picking successive numbers. This dependency is not ideal, but + # makes the test much easier to write. + [tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = ( + GetTestsForAllIterations( + {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)])) + + # Make sure running the tests with random seed 1 gets the same + # order as in iteration 1 above. + [tests_with_seed1] = GetTestsForAllIterations( + {}, [ShuffleFlag(), RandomSeedFlag(1)]) + self.assertEqual(tests_in_iteration1, tests_with_seed1) + + # Make sure running the tests with random seed 2 gets the same + # order as in iteration 2 above. Success means that Google Test + # correctly restores the test order before re-shuffling at the + # beginning of iteration 2. + [tests_with_seed2] = GetTestsForAllIterations( + {}, [ShuffleFlag(), RandomSeedFlag(2)]) + self.assertEqual(tests_in_iteration2, tests_with_seed2) + + # Make sure running the tests with random seed 3 gets the same + # order as in iteration 3 above. Success means that Google Test + # correctly restores the test order before re-shuffling at the + # beginning of iteration 3. + [tests_with_seed3] = GetTestsForAllIterations( + {}, [ShuffleFlag(), RandomSeedFlag(3)]) + self.assertEqual(tests_in_iteration3, tests_with_seed3) + + def testShuffleGeneratesNewOrderInEachIteration(self): + [tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = ( + GetTestsForAllIterations( + {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)])) + + self.assert_(tests_in_iteration1 != tests_in_iteration2, + tests_in_iteration1) + self.assert_(tests_in_iteration1 != tests_in_iteration3, + tests_in_iteration1) + self.assert_(tests_in_iteration2 != tests_in_iteration3, + tests_in_iteration2) + + def testShuffleShardedTestsPreservesPartition(self): + # If we run M tests on N shards, the same M tests should be run in + # total, regardless of the random seeds used by the shards. + [tests1] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', + SHARD_INDEX_ENV_VAR: '0'}, + [ShuffleFlag(), RandomSeedFlag(1)]) + [tests2] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', + SHARD_INDEX_ENV_VAR: '1'}, + [ShuffleFlag(), RandomSeedFlag(20)]) + [tests3] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', + SHARD_INDEX_ENV_VAR: '2'}, + [ShuffleFlag(), RandomSeedFlag(25)]) + sorted_sharded_tests = tests1 + tests2 + tests3 + sorted_sharded_tests.sort() + sorted_active_tests = [] + sorted_active_tests.extend(ACTIVE_TESTS) + sorted_active_tests.sort() + self.assertEqual(sorted_active_tests, sorted_sharded_tests) + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/googletest-shuffle-test_.cc b/googletest/test/googletest-shuffle-test_.cc new file mode 100644 index 0000000..6fb441b --- /dev/null +++ b/googletest/test/googletest-shuffle-test_.cc @@ -0,0 +1,103 @@ +// Copyright 2009, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Verifies that test shuffling works. + +#include "gtest/gtest.h" + +namespace { + +using ::testing::EmptyTestEventListener; +using ::testing::InitGoogleTest; +using ::testing::Message; +using ::testing::Test; +using ::testing::TestEventListeners; +using ::testing::TestInfo; +using ::testing::UnitTest; +using ::testing::internal::scoped_ptr; + +// The test methods are empty, as the sole purpose of this program is +// to print the test names before/after shuffling. + +class A : public Test {}; +TEST_F(A, A) {} +TEST_F(A, B) {} + +TEST(ADeathTest, A) {} +TEST(ADeathTest, B) {} +TEST(ADeathTest, C) {} + +TEST(B, A) {} +TEST(B, B) {} +TEST(B, C) {} +TEST(B, DISABLED_D) {} +TEST(B, DISABLED_E) {} + +TEST(BDeathTest, A) {} +TEST(BDeathTest, B) {} + +TEST(C, A) {} +TEST(C, B) {} +TEST(C, C) {} +TEST(C, DISABLED_D) {} + +TEST(CDeathTest, A) {} + +TEST(DISABLED_D, A) {} +TEST(DISABLED_D, DISABLED_B) {} + +// This printer prints the full test names only, starting each test +// iteration with a "----" marker. +class TestNamePrinter : public EmptyTestEventListener { + public: + virtual void OnTestIterationStart(const UnitTest& /* unit_test */, + int /* iteration */) { + printf("----\n"); + } + + virtual void OnTestStart(const TestInfo& test_info) { + printf("%s.%s\n", test_info.test_case_name(), test_info.name()); + } +}; + +} // namespace + +int main(int argc, char **argv) { + InitGoogleTest(&argc, argv); + + // Replaces the default printer with TestNamePrinter, which prints + // the test name only. + TestEventListeners& listeners = UnitTest::GetInstance()->listeners(); + delete listeners.Release(listeners.default_result_printer()); + listeners.Append(new TestNamePrinter); + + return RUN_ALL_TESTS(); +} diff --git a/googletest/test/gtest_catch_exceptions_test.py b/googletest/test/gtest_catch_exceptions_test.py deleted file mode 100755 index 760f914..0000000 --- a/googletest/test/gtest_catch_exceptions_test.py +++ /dev/null @@ -1,235 +0,0 @@ -#!/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 gtest_test_utils - -# Constants. -FLAG_PREFIX = '--gtest_' -LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests' -NO_CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions=0' -FILTER_FLAG = FLAG_PREFIX + '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_') - -environ = gtest_test_utils.environ -SetEnvVar = gtest_test_utils.SetEnvVar - -# Tests in this file run a Google-Test-based test program and expect it -# to terminate prematurely. Therefore they are incompatible with -# the premature-exit-file protocol by design. Unset the -# premature-exit filepath to prevent Google Test from creating -# the file. -SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None) - -TEST_LIST = gtest_test_utils.Subprocess( - [EXE_PATH, LIST_TESTS_FLAG], env=environ).output - -SUPPORTS_SEH_EXCEPTIONS = 'ThrowsSehException' in TEST_LIST - -if SUPPORTS_SEH_EXCEPTIONS: - BINARY_OUTPUT = gtest_test_utils.Subprocess([EXE_PATH], env=environ).output - -EX_BINARY_OUTPUT = gtest_test_utils.Subprocess( - [EX_EXE_PATH], env=environ).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"') - - if ('CxxExceptionInDestructorTest.ThrowsExceptionInDestructor' in - EX_BINARY_OUTPUT): - - 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, - NO_CATCH_EXCEPTIONS_FLAG, - FITLER_OUT_SEH_TESTS_FLAG], - env=environ).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/googletest/test/gtest_catch_exceptions_test_.cc b/googletest/test/gtest_catch_exceptions_test_.cc deleted file mode 100644 index c6d953c..0000000 --- a/googletest/test/gtest_catch_exceptions_test_.cc +++ /dev/null @@ -1,311 +0,0 @@ -// 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 // NOLINT -#include // For exit(). - -#if GTEST_HAS_SEH -# include -#endif - -#if GTEST_HAS_EXCEPTIONS -# include // For set_terminate(). -# include -#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."; -} - -// Exceptions in destructors are not supported in C++11. -#if !GTEST_LANG_CXX11 -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) {} -#endif // C++11 mode - -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/googletest/test/gtest_shuffle_test.py b/googletest/test/gtest_shuffle_test.py deleted file mode 100755 index 30d0303..0000000 --- a/googletest/test/gtest_shuffle_test.py +++ /dev/null @@ -1,325 +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. - -"""Verifies that test shuffling works.""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import os -import gtest_test_utils - -# Command to run the gtest_shuffle_test_ program. -COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_shuffle_test_') - -# The environment variables for test sharding. -TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS' -SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX' - -TEST_FILTER = 'A*.A:A*.B:C*' - -ALL_TESTS = [] -ACTIVE_TESTS = [] -FILTERED_TESTS = [] -SHARDED_TESTS = [] - -SHUFFLED_ALL_TESTS = [] -SHUFFLED_ACTIVE_TESTS = [] -SHUFFLED_FILTERED_TESTS = [] -SHUFFLED_SHARDED_TESTS = [] - - -def AlsoRunDisabledTestsFlag(): - return '--gtest_also_run_disabled_tests' - - -def FilterFlag(test_filter): - return '--gtest_filter=%s' % (test_filter,) - - -def RepeatFlag(n): - return '--gtest_repeat=%s' % (n,) - - -def ShuffleFlag(): - return '--gtest_shuffle' - - -def RandomSeedFlag(n): - return '--gtest_random_seed=%s' % (n,) - - -def RunAndReturnOutput(extra_env, args): - """Runs the test program and returns its output.""" - - environ_copy = os.environ.copy() - environ_copy.update(extra_env) - - return gtest_test_utils.Subprocess([COMMAND] + args, env=environ_copy).output - - -def GetTestsForAllIterations(extra_env, args): - """Runs the test program and returns a list of test lists. - - Args: - extra_env: a map from environment variables to their values - args: command line flags to pass to gtest_shuffle_test_ - - Returns: - A list where the i-th element is the list of tests run in the i-th - test iteration. - """ - - test_iterations = [] - for line in RunAndReturnOutput(extra_env, args).split('\n'): - if line.startswith('----'): - tests = [] - test_iterations.append(tests) - elif line.strip(): - tests.append(line.strip()) # 'TestCaseName.TestName' - - return test_iterations - - -def GetTestCases(tests): - """Returns a list of test cases in the given full test names. - - Args: - tests: a list of full test names - - Returns: - A list of test cases from 'tests', in their original order. - Consecutive duplicates are removed. - """ - - test_cases = [] - for test in tests: - test_case = test.split('.')[0] - if not test_case in test_cases: - test_cases.append(test_case) - - return test_cases - - -def CalculateTestLists(): - """Calculates the list of tests run under different flags.""" - - if not ALL_TESTS: - ALL_TESTS.extend( - GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0]) - - if not ACTIVE_TESTS: - ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [])[0]) - - if not FILTERED_TESTS: - FILTERED_TESTS.extend( - GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0]) - - if not SHARDED_TESTS: - SHARDED_TESTS.extend( - GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', - SHARD_INDEX_ENV_VAR: '1'}, - [])[0]) - - if not SHUFFLED_ALL_TESTS: - SHUFFLED_ALL_TESTS.extend(GetTestsForAllIterations( - {}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)])[0]) - - if not SHUFFLED_ACTIVE_TESTS: - SHUFFLED_ACTIVE_TESTS.extend(GetTestsForAllIterations( - {}, [ShuffleFlag(), RandomSeedFlag(1)])[0]) - - if not SHUFFLED_FILTERED_TESTS: - SHUFFLED_FILTERED_TESTS.extend(GetTestsForAllIterations( - {}, [ShuffleFlag(), RandomSeedFlag(1), FilterFlag(TEST_FILTER)])[0]) - - if not SHUFFLED_SHARDED_TESTS: - SHUFFLED_SHARDED_TESTS.extend( - GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', - SHARD_INDEX_ENV_VAR: '1'}, - [ShuffleFlag(), RandomSeedFlag(1)])[0]) - - -class GTestShuffleUnitTest(gtest_test_utils.TestCase): - """Tests test shuffling.""" - - def setUp(self): - CalculateTestLists() - - def testShufflePreservesNumberOfTests(self): - self.assertEqual(len(ALL_TESTS), len(SHUFFLED_ALL_TESTS)) - self.assertEqual(len(ACTIVE_TESTS), len(SHUFFLED_ACTIVE_TESTS)) - self.assertEqual(len(FILTERED_TESTS), len(SHUFFLED_FILTERED_TESTS)) - self.assertEqual(len(SHARDED_TESTS), len(SHUFFLED_SHARDED_TESTS)) - - def testShuffleChangesTestOrder(self): - self.assert_(SHUFFLED_ALL_TESTS != ALL_TESTS, SHUFFLED_ALL_TESTS) - self.assert_(SHUFFLED_ACTIVE_TESTS != ACTIVE_TESTS, SHUFFLED_ACTIVE_TESTS) - self.assert_(SHUFFLED_FILTERED_TESTS != FILTERED_TESTS, - SHUFFLED_FILTERED_TESTS) - self.assert_(SHUFFLED_SHARDED_TESTS != SHARDED_TESTS, - SHUFFLED_SHARDED_TESTS) - - def testShuffleChangesTestCaseOrder(self): - self.assert_(GetTestCases(SHUFFLED_ALL_TESTS) != GetTestCases(ALL_TESTS), - GetTestCases(SHUFFLED_ALL_TESTS)) - self.assert_( - GetTestCases(SHUFFLED_ACTIVE_TESTS) != GetTestCases(ACTIVE_TESTS), - GetTestCases(SHUFFLED_ACTIVE_TESTS)) - self.assert_( - GetTestCases(SHUFFLED_FILTERED_TESTS) != GetTestCases(FILTERED_TESTS), - GetTestCases(SHUFFLED_FILTERED_TESTS)) - self.assert_( - GetTestCases(SHUFFLED_SHARDED_TESTS) != GetTestCases(SHARDED_TESTS), - GetTestCases(SHUFFLED_SHARDED_TESTS)) - - def testShuffleDoesNotRepeatTest(self): - for test in SHUFFLED_ALL_TESTS: - self.assertEqual(1, SHUFFLED_ALL_TESTS.count(test), - '%s appears more than once' % (test,)) - for test in SHUFFLED_ACTIVE_TESTS: - self.assertEqual(1, SHUFFLED_ACTIVE_TESTS.count(test), - '%s appears more than once' % (test,)) - for test in SHUFFLED_FILTERED_TESTS: - self.assertEqual(1, SHUFFLED_FILTERED_TESTS.count(test), - '%s appears more than once' % (test,)) - for test in SHUFFLED_SHARDED_TESTS: - self.assertEqual(1, SHUFFLED_SHARDED_TESTS.count(test), - '%s appears more than once' % (test,)) - - def testShuffleDoesNotCreateNewTest(self): - for test in SHUFFLED_ALL_TESTS: - self.assert_(test in ALL_TESTS, '%s is an invalid test' % (test,)) - for test in SHUFFLED_ACTIVE_TESTS: - self.assert_(test in ACTIVE_TESTS, '%s is an invalid test' % (test,)) - for test in SHUFFLED_FILTERED_TESTS: - self.assert_(test in FILTERED_TESTS, '%s is an invalid test' % (test,)) - for test in SHUFFLED_SHARDED_TESTS: - self.assert_(test in SHARDED_TESTS, '%s is an invalid test' % (test,)) - - def testShuffleIncludesAllTests(self): - for test in ALL_TESTS: - self.assert_(test in SHUFFLED_ALL_TESTS, '%s is missing' % (test,)) - for test in ACTIVE_TESTS: - self.assert_(test in SHUFFLED_ACTIVE_TESTS, '%s is missing' % (test,)) - for test in FILTERED_TESTS: - self.assert_(test in SHUFFLED_FILTERED_TESTS, '%s is missing' % (test,)) - for test in SHARDED_TESTS: - self.assert_(test in SHUFFLED_SHARDED_TESTS, '%s is missing' % (test,)) - - def testShuffleLeavesDeathTestsAtFront(self): - non_death_test_found = False - for test in SHUFFLED_ACTIVE_TESTS: - if 'DeathTest.' in test: - self.assert_(not non_death_test_found, - '%s appears after a non-death test' % (test,)) - else: - non_death_test_found = True - - def _VerifyTestCasesDoNotInterleave(self, tests): - test_cases = [] - for test in tests: - [test_case, _] = test.split('.') - if test_cases and test_cases[-1] != test_case: - test_cases.append(test_case) - self.assertEqual(1, test_cases.count(test_case), - 'Test case %s is not grouped together in %s' % - (test_case, tests)) - - def testShuffleDoesNotInterleaveTestCases(self): - self._VerifyTestCasesDoNotInterleave(SHUFFLED_ALL_TESTS) - self._VerifyTestCasesDoNotInterleave(SHUFFLED_ACTIVE_TESTS) - self._VerifyTestCasesDoNotInterleave(SHUFFLED_FILTERED_TESTS) - self._VerifyTestCasesDoNotInterleave(SHUFFLED_SHARDED_TESTS) - - def testShuffleRestoresOrderAfterEachIteration(self): - # Get the test lists in all 3 iterations, using random seed 1, 2, - # and 3 respectively. Google Test picks a different seed in each - # iteration, and this test depends on the current implementation - # picking successive numbers. This dependency is not ideal, but - # makes the test much easier to write. - [tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = ( - GetTestsForAllIterations( - {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)])) - - # Make sure running the tests with random seed 1 gets the same - # order as in iteration 1 above. - [tests_with_seed1] = GetTestsForAllIterations( - {}, [ShuffleFlag(), RandomSeedFlag(1)]) - self.assertEqual(tests_in_iteration1, tests_with_seed1) - - # Make sure running the tests with random seed 2 gets the same - # order as in iteration 2 above. Success means that Google Test - # correctly restores the test order before re-shuffling at the - # beginning of iteration 2. - [tests_with_seed2] = GetTestsForAllIterations( - {}, [ShuffleFlag(), RandomSeedFlag(2)]) - self.assertEqual(tests_in_iteration2, tests_with_seed2) - - # Make sure running the tests with random seed 3 gets the same - # order as in iteration 3 above. Success means that Google Test - # correctly restores the test order before re-shuffling at the - # beginning of iteration 3. - [tests_with_seed3] = GetTestsForAllIterations( - {}, [ShuffleFlag(), RandomSeedFlag(3)]) - self.assertEqual(tests_in_iteration3, tests_with_seed3) - - def testShuffleGeneratesNewOrderInEachIteration(self): - [tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = ( - GetTestsForAllIterations( - {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)])) - - self.assert_(tests_in_iteration1 != tests_in_iteration2, - tests_in_iteration1) - self.assert_(tests_in_iteration1 != tests_in_iteration3, - tests_in_iteration1) - self.assert_(tests_in_iteration2 != tests_in_iteration3, - tests_in_iteration2) - - def testShuffleShardedTestsPreservesPartition(self): - # If we run M tests on N shards, the same M tests should be run in - # total, regardless of the random seeds used by the shards. - [tests1] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', - SHARD_INDEX_ENV_VAR: '0'}, - [ShuffleFlag(), RandomSeedFlag(1)]) - [tests2] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', - SHARD_INDEX_ENV_VAR: '1'}, - [ShuffleFlag(), RandomSeedFlag(20)]) - [tests3] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', - SHARD_INDEX_ENV_VAR: '2'}, - [ShuffleFlag(), RandomSeedFlag(25)]) - sorted_sharded_tests = tests1 + tests2 + tests3 - sorted_sharded_tests.sort() - sorted_active_tests = [] - sorted_active_tests.extend(ACTIVE_TESTS) - sorted_active_tests.sort() - self.assertEqual(sorted_active_tests, sorted_sharded_tests) - -if __name__ == '__main__': - gtest_test_utils.Main() diff --git a/googletest/test/gtest_shuffle_test_.cc b/googletest/test/gtest_shuffle_test_.cc deleted file mode 100644 index 6fb441b..0000000 --- a/googletest/test/gtest_shuffle_test_.cc +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2009, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) - -// Verifies that test shuffling works. - -#include "gtest/gtest.h" - -namespace { - -using ::testing::EmptyTestEventListener; -using ::testing::InitGoogleTest; -using ::testing::Message; -using ::testing::Test; -using ::testing::TestEventListeners; -using ::testing::TestInfo; -using ::testing::UnitTest; -using ::testing::internal::scoped_ptr; - -// The test methods are empty, as the sole purpose of this program is -// to print the test names before/after shuffling. - -class A : public Test {}; -TEST_F(A, A) {} -TEST_F(A, B) {} - -TEST(ADeathTest, A) {} -TEST(ADeathTest, B) {} -TEST(ADeathTest, C) {} - -TEST(B, A) {} -TEST(B, B) {} -TEST(B, C) {} -TEST(B, DISABLED_D) {} -TEST(B, DISABLED_E) {} - -TEST(BDeathTest, A) {} -TEST(BDeathTest, B) {} - -TEST(C, A) {} -TEST(C, B) {} -TEST(C, C) {} -TEST(C, DISABLED_D) {} - -TEST(CDeathTest, A) {} - -TEST(DISABLED_D, A) {} -TEST(DISABLED_D, DISABLED_B) {} - -// This printer prints the full test names only, starting each test -// iteration with a "----" marker. -class TestNamePrinter : public EmptyTestEventListener { - public: - virtual void OnTestIterationStart(const UnitTest& /* unit_test */, - int /* iteration */) { - printf("----\n"); - } - - virtual void OnTestStart(const TestInfo& test_info) { - printf("%s.%s\n", test_info.test_case_name(), test_info.name()); - } -}; - -} // namespace - -int main(int argc, char **argv) { - InitGoogleTest(&argc, argv); - - // Replaces the default printer with TestNamePrinter, which prints - // the test name only. - TestEventListeners& listeners = UnitTest::GetInstance()->listeners(); - delete listeners.Release(listeners.default_result_printer()); - listeners.Append(new TestNamePrinter); - - return RUN_ALL_TESTS(); -} -- cgit v0.12 From b888e23fce40dfd2266e0c88e54afde45c5d23f0 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 13:49:29 -0400 Subject: googletest list tests unitest --- googletest/test/BUILD.bazel | 10 +- googletest/test/googletest-list-tests-unittest.py | 207 +++++++++++++++++++++ googletest/test/googletest-list-tests-unittest_.cc | 157 ++++++++++++++++ googletest/test/gtest_list_tests_unittest.py | 207 --------------------- googletest/test/gtest_list_tests_unittest_.cc | 157 ---------------- 5 files changed, 369 insertions(+), 369 deletions(-) create mode 100755 googletest/test/googletest-list-tests-unittest.py create mode 100644 googletest/test/googletest-list-tests-unittest_.cc delete mode 100755 googletest/test/gtest_list_tests_unittest.py delete mode 100644 googletest/test/gtest_list_tests_unittest_.cc diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 319c849..360ce26 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -282,17 +282,17 @@ py_test( cc_binary( - name = "gtest_list_tests_unittest_", + name = "googletest-list-tests-unittest_", testonly = 1, - srcs = ["gtest_list_tests_unittest_.cc"], + srcs = ["googletest-list-tests-unittest_.cc"], deps = ["//:gtest"], ) py_test( - name = "gtest_list_tests_unittest", + name = "googletest-list-tests-unittest", size = "small", - srcs = ["gtest_list_tests_unittest.py"], - data = [":gtest_list_tests_unittest_"], + srcs = ["googletest-list-tests-unittest.py"], + data = [":googletest-list-tests-unittest_"], deps = [":gtest_test_utils"], ) diff --git a/googletest/test/googletest-list-tests-unittest.py b/googletest/test/googletest-list-tests-unittest.py new file mode 100755 index 0000000..a38073a --- /dev/null +++ b/googletest/test/googletest-list-tests-unittest.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python +# +# Copyright 2006, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Unit test for Google Test's --gtest_list_tests flag. + +A user can ask Google Test to list all tests by specifying the +--gtest_list_tests flag. This script tests such functionality +by invoking googletest-list-tests-unittest_ (a program written with +Google Test) the command line flags. +""" + +__author__ = 'phanna@google.com (Patrick Hanna)' + +import re +import gtest_test_utils + +# Constants. + +# The command line flag for enabling/disabling listing all tests. +LIST_TESTS_FLAG = 'gtest_list_tests' + +# Path to the googletest-list-tests-unittest_ program. +EXE_PATH = gtest_test_utils.GetTestExecutablePath('googletest-list-tests-unittest_') + +# The expected output when running googletest-list-tests-unittest_ with +# --gtest_list_tests +EXPECTED_OUTPUT_NO_FILTER_RE = re.compile(r"""FooDeathTest\. + Test1 +Foo\. + Bar1 + Bar2 + DISABLED_Bar3 +Abc\. + Xyz + Def +FooBar\. + Baz +FooTest\. + Test1 + DISABLED_Test2 + Test3 +TypedTest/0\. # TypeParam = (VeryLo{245}|class VeryLo{239})\.\.\. + TestA + TestB +TypedTest/1\. # TypeParam = int\s*\*( __ptr64)? + TestA + TestB +TypedTest/2\. # TypeParam = .*MyArray + TestA + TestB +My/TypeParamTest/0\. # TypeParam = (VeryLo{245}|class VeryLo{239})\.\.\. + TestA + TestB +My/TypeParamTest/1\. # TypeParam = int\s*\*( __ptr64)? + TestA + TestB +My/TypeParamTest/2\. # TypeParam = .*MyArray + TestA + TestB +MyInstantiation/ValueParamTest\. + TestA/0 # GetParam\(\) = one line + TestA/1 # GetParam\(\) = two\\nlines + TestA/2 # GetParam\(\) = a very\\nlo{241}\.\.\. + TestB/0 # GetParam\(\) = one line + TestB/1 # GetParam\(\) = two\\nlines + TestB/2 # GetParam\(\) = a very\\nlo{241}\.\.\. +""") + +# The expected output when running googletest-list-tests-unittest_ with +# --gtest_list_tests and --gtest_filter=Foo*. +EXPECTED_OUTPUT_FILTER_FOO_RE = re.compile(r"""FooDeathTest\. + Test1 +Foo\. + Bar1 + Bar2 + DISABLED_Bar3 +FooBar\. + Baz +FooTest\. + Test1 + DISABLED_Test2 + Test3 +""") + +# Utilities. + + +def Run(args): + """Runs googletest-list-tests-unittest_ and returns the list of tests printed.""" + + return gtest_test_utils.Subprocess([EXE_PATH] + args, + capture_stderr=False).output + + +# The unit test. + + +class GTestListTestsUnitTest(gtest_test_utils.TestCase): + """Tests using the --gtest_list_tests flag to list all tests.""" + + def RunAndVerify(self, flag_value, expected_output_re, other_flag): + """Runs googletest-list-tests-unittest_ and verifies that it prints + the correct tests. + + Args: + flag_value: value of the --gtest_list_tests flag; + None if the flag should not be present. + expected_output_re: regular expression that matches the expected + output after running command; + other_flag: a different flag to be passed to command + along with gtest_list_tests; + None if the flag should not be present. + """ + + if flag_value is None: + flag = '' + flag_expression = 'not set' + elif flag_value == '0': + flag = '--%s=0' % LIST_TESTS_FLAG + flag_expression = '0' + else: + flag = '--%s' % LIST_TESTS_FLAG + flag_expression = '1' + + args = [flag] + + if other_flag is not None: + args += [other_flag] + + output = Run(args) + + if expected_output_re: + self.assert_( + expected_output_re.match(output), + ('when %s is %s, the output of "%s" is "%s",\n' + 'which does not match regex "%s"' % + (LIST_TESTS_FLAG, flag_expression, ' '.join(args), output, + expected_output_re.pattern))) + else: + self.assert_( + not EXPECTED_OUTPUT_NO_FILTER_RE.match(output), + ('when %s is %s, the output of "%s" is "%s"'% + (LIST_TESTS_FLAG, flag_expression, ' '.join(args), output))) + + def testDefaultBehavior(self): + """Tests the behavior of the default mode.""" + + self.RunAndVerify(flag_value=None, + expected_output_re=None, + other_flag=None) + + def testFlag(self): + """Tests using the --gtest_list_tests flag.""" + + self.RunAndVerify(flag_value='0', + expected_output_re=None, + other_flag=None) + self.RunAndVerify(flag_value='1', + expected_output_re=EXPECTED_OUTPUT_NO_FILTER_RE, + other_flag=None) + + def testOverrideNonFilterFlags(self): + """Tests that --gtest_list_tests overrides the non-filter flags.""" + + self.RunAndVerify(flag_value='1', + expected_output_re=EXPECTED_OUTPUT_NO_FILTER_RE, + other_flag='--gtest_break_on_failure') + + def testWithFilterFlags(self): + """Tests that --gtest_list_tests takes into account the + --gtest_filter flag.""" + + self.RunAndVerify(flag_value='1', + expected_output_re=EXPECTED_OUTPUT_FILTER_FOO_RE, + other_flag='--gtest_filter=Foo*') + + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/googletest-list-tests-unittest_.cc b/googletest/test/googletest-list-tests-unittest_.cc new file mode 100644 index 0000000..907c176 --- /dev/null +++ b/googletest/test/googletest-list-tests-unittest_.cc @@ -0,0 +1,157 @@ +// Copyright 2006, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: phanna@google.com (Patrick Hanna) + +// Unit test for Google Test's --gtest_list_tests flag. +// +// A user can ask Google Test to list all tests that will run +// so that when using a filter, a user will know what +// tests to look for. The tests will not be run after listing. +// +// This program will be invoked from a Python unit test. +// Don't run it directly. + +#include "gtest/gtest.h" + +// Several different test cases and tests that will be listed. +TEST(Foo, Bar1) { +} + +TEST(Foo, Bar2) { +} + +TEST(Foo, DISABLED_Bar3) { +} + +TEST(Abc, Xyz) { +} + +TEST(Abc, Def) { +} + +TEST(FooBar, Baz) { +} + +class FooTest : public testing::Test { +}; + +TEST_F(FooTest, Test1) { +} + +TEST_F(FooTest, DISABLED_Test2) { +} + +TEST_F(FooTest, Test3) { +} + +TEST(FooDeathTest, Test1) { +} + +// A group of value-parameterized tests. + +class MyType { + public: + explicit MyType(const std::string& a_value) : value_(a_value) {} + + const std::string& value() const { return value_; } + + private: + std::string value_; +}; + +// Teaches Google Test how to print a MyType. +void PrintTo(const MyType& x, std::ostream* os) { + *os << x.value(); +} + +class ValueParamTest : public testing::TestWithParam { +}; + +TEST_P(ValueParamTest, TestA) { +} + +TEST_P(ValueParamTest, TestB) { +} + +INSTANTIATE_TEST_CASE_P( + MyInstantiation, ValueParamTest, + testing::Values(MyType("one line"), + MyType("two\nlines"), + MyType("a very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line"))); // NOLINT + +// A group of typed tests. + +// A deliberately long type name for testing the line-truncating +// behavior when printing a type parameter. +class VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName { // NOLINT +}; + +template +class TypedTest : public testing::Test { +}; + +template +class MyArray { +}; + +typedef testing::Types > MyTypes; + +TYPED_TEST_CASE(TypedTest, MyTypes); + +TYPED_TEST(TypedTest, TestA) { +} + +TYPED_TEST(TypedTest, TestB) { +} + +// A group of type-parameterized tests. + +template +class TypeParamTest : public testing::Test { +}; + +TYPED_TEST_CASE_P(TypeParamTest); + +TYPED_TEST_P(TypeParamTest, TestA) { +} + +TYPED_TEST_P(TypeParamTest, TestB) { +} + +REGISTER_TYPED_TEST_CASE_P(TypeParamTest, TestA, TestB); + +INSTANTIATE_TYPED_TEST_CASE_P(My, TypeParamTest, MyTypes); + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + + return RUN_ALL_TESTS(); +} diff --git a/googletest/test/gtest_list_tests_unittest.py b/googletest/test/gtest_list_tests_unittest.py deleted file mode 100755 index ebf1a3c..0000000 --- a/googletest/test/gtest_list_tests_unittest.py +++ /dev/null @@ -1,207 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2006, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Unit test for Google Test's --gtest_list_tests flag. - -A user can ask Google Test to list all tests by specifying the ---gtest_list_tests flag. This script tests such functionality -by invoking gtest_list_tests_unittest_ (a program written with -Google Test) the command line flags. -""" - -__author__ = 'phanna@google.com (Patrick Hanna)' - -import re -import gtest_test_utils - -# Constants. - -# The command line flag for enabling/disabling listing all tests. -LIST_TESTS_FLAG = 'gtest_list_tests' - -# Path to the gtest_list_tests_unittest_ program. -EXE_PATH = gtest_test_utils.GetTestExecutablePath('gtest_list_tests_unittest_') - -# The expected output when running gtest_list_tests_unittest_ with -# --gtest_list_tests -EXPECTED_OUTPUT_NO_FILTER_RE = re.compile(r"""FooDeathTest\. - Test1 -Foo\. - Bar1 - Bar2 - DISABLED_Bar3 -Abc\. - Xyz - Def -FooBar\. - Baz -FooTest\. - Test1 - DISABLED_Test2 - Test3 -TypedTest/0\. # TypeParam = (VeryLo{245}|class VeryLo{239})\.\.\. - TestA - TestB -TypedTest/1\. # TypeParam = int\s*\*( __ptr64)? - TestA - TestB -TypedTest/2\. # TypeParam = .*MyArray - TestA - TestB -My/TypeParamTest/0\. # TypeParam = (VeryLo{245}|class VeryLo{239})\.\.\. - TestA - TestB -My/TypeParamTest/1\. # TypeParam = int\s*\*( __ptr64)? - TestA - TestB -My/TypeParamTest/2\. # TypeParam = .*MyArray - TestA - TestB -MyInstantiation/ValueParamTest\. - TestA/0 # GetParam\(\) = one line - TestA/1 # GetParam\(\) = two\\nlines - TestA/2 # GetParam\(\) = a very\\nlo{241}\.\.\. - TestB/0 # GetParam\(\) = one line - TestB/1 # GetParam\(\) = two\\nlines - TestB/2 # GetParam\(\) = a very\\nlo{241}\.\.\. -""") - -# The expected output when running gtest_list_tests_unittest_ with -# --gtest_list_tests and --gtest_filter=Foo*. -EXPECTED_OUTPUT_FILTER_FOO_RE = re.compile(r"""FooDeathTest\. - Test1 -Foo\. - Bar1 - Bar2 - DISABLED_Bar3 -FooBar\. - Baz -FooTest\. - Test1 - DISABLED_Test2 - Test3 -""") - -# Utilities. - - -def Run(args): - """Runs gtest_list_tests_unittest_ and returns the list of tests printed.""" - - return gtest_test_utils.Subprocess([EXE_PATH] + args, - capture_stderr=False).output - - -# The unit test. - - -class GTestListTestsUnitTest(gtest_test_utils.TestCase): - """Tests using the --gtest_list_tests flag to list all tests.""" - - def RunAndVerify(self, flag_value, expected_output_re, other_flag): - """Runs gtest_list_tests_unittest_ and verifies that it prints - the correct tests. - - Args: - flag_value: value of the --gtest_list_tests flag; - None if the flag should not be present. - expected_output_re: regular expression that matches the expected - output after running command; - other_flag: a different flag to be passed to command - along with gtest_list_tests; - None if the flag should not be present. - """ - - if flag_value is None: - flag = '' - flag_expression = 'not set' - elif flag_value == '0': - flag = '--%s=0' % LIST_TESTS_FLAG - flag_expression = '0' - else: - flag = '--%s' % LIST_TESTS_FLAG - flag_expression = '1' - - args = [flag] - - if other_flag is not None: - args += [other_flag] - - output = Run(args) - - if expected_output_re: - self.assert_( - expected_output_re.match(output), - ('when %s is %s, the output of "%s" is "%s",\n' - 'which does not match regex "%s"' % - (LIST_TESTS_FLAG, flag_expression, ' '.join(args), output, - expected_output_re.pattern))) - else: - self.assert_( - not EXPECTED_OUTPUT_NO_FILTER_RE.match(output), - ('when %s is %s, the output of "%s" is "%s"'% - (LIST_TESTS_FLAG, flag_expression, ' '.join(args), output))) - - def testDefaultBehavior(self): - """Tests the behavior of the default mode.""" - - self.RunAndVerify(flag_value=None, - expected_output_re=None, - other_flag=None) - - def testFlag(self): - """Tests using the --gtest_list_tests flag.""" - - self.RunAndVerify(flag_value='0', - expected_output_re=None, - other_flag=None) - self.RunAndVerify(flag_value='1', - expected_output_re=EXPECTED_OUTPUT_NO_FILTER_RE, - other_flag=None) - - def testOverrideNonFilterFlags(self): - """Tests that --gtest_list_tests overrides the non-filter flags.""" - - self.RunAndVerify(flag_value='1', - expected_output_re=EXPECTED_OUTPUT_NO_FILTER_RE, - other_flag='--gtest_break_on_failure') - - def testWithFilterFlags(self): - """Tests that --gtest_list_tests takes into account the - --gtest_filter flag.""" - - self.RunAndVerify(flag_value='1', - expected_output_re=EXPECTED_OUTPUT_FILTER_FOO_RE, - other_flag='--gtest_filter=Foo*') - - -if __name__ == '__main__': - gtest_test_utils.Main() diff --git a/googletest/test/gtest_list_tests_unittest_.cc b/googletest/test/gtest_list_tests_unittest_.cc deleted file mode 100644 index 907c176..0000000 --- a/googletest/test/gtest_list_tests_unittest_.cc +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: phanna@google.com (Patrick Hanna) - -// Unit test for Google Test's --gtest_list_tests flag. -// -// A user can ask Google Test to list all tests that will run -// so that when using a filter, a user will know what -// tests to look for. The tests will not be run after listing. -// -// This program will be invoked from a Python unit test. -// Don't run it directly. - -#include "gtest/gtest.h" - -// Several different test cases and tests that will be listed. -TEST(Foo, Bar1) { -} - -TEST(Foo, Bar2) { -} - -TEST(Foo, DISABLED_Bar3) { -} - -TEST(Abc, Xyz) { -} - -TEST(Abc, Def) { -} - -TEST(FooBar, Baz) { -} - -class FooTest : public testing::Test { -}; - -TEST_F(FooTest, Test1) { -} - -TEST_F(FooTest, DISABLED_Test2) { -} - -TEST_F(FooTest, Test3) { -} - -TEST(FooDeathTest, Test1) { -} - -// A group of value-parameterized tests. - -class MyType { - public: - explicit MyType(const std::string& a_value) : value_(a_value) {} - - const std::string& value() const { return value_; } - - private: - std::string value_; -}; - -// Teaches Google Test how to print a MyType. -void PrintTo(const MyType& x, std::ostream* os) { - *os << x.value(); -} - -class ValueParamTest : public testing::TestWithParam { -}; - -TEST_P(ValueParamTest, TestA) { -} - -TEST_P(ValueParamTest, TestB) { -} - -INSTANTIATE_TEST_CASE_P( - MyInstantiation, ValueParamTest, - testing::Values(MyType("one line"), - MyType("two\nlines"), - MyType("a very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line"))); // NOLINT - -// A group of typed tests. - -// A deliberately long type name for testing the line-truncating -// behavior when printing a type parameter. -class VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName { // NOLINT -}; - -template -class TypedTest : public testing::Test { -}; - -template -class MyArray { -}; - -typedef testing::Types > MyTypes; - -TYPED_TEST_CASE(TypedTest, MyTypes); - -TYPED_TEST(TypedTest, TestA) { -} - -TYPED_TEST(TypedTest, TestB) { -} - -// A group of type-parameterized tests. - -template -class TypeParamTest : public testing::Test { -}; - -TYPED_TEST_CASE_P(TypeParamTest); - -TYPED_TEST_P(TypeParamTest, TestA) { -} - -TYPED_TEST_P(TypeParamTest, TestB) { -} - -REGISTER_TYPED_TEST_CASE_P(TypeParamTest, TestA, TestB); - -INSTANTIATE_TYPED_TEST_CASE_P(My, TypeParamTest, MyTypes); - -int main(int argc, char **argv) { - ::testing::InitGoogleTest(&argc, argv); - - return RUN_ALL_TESTS(); -} -- cgit v0.12 From 96077bc9f37cdc3d9c182ba78ef0a2560099aced Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 15:02:28 -0400 Subject: more tests changes --- googletest/test/BUILD.bazel | 30 +- googletest/test/googletest-death-test-test.cc | 1424 +++++++++++++++++++++ googletest/test/googletest-uninitialized-test.py | 69 + googletest/test/googletest-uninitialized-test_.cc | 43 + googletest/test/gtest-death-test_test.cc | 1424 --------------------- googletest/test/gtest_uninitialized_test.py | 69 - 6 files changed, 1561 insertions(+), 1498 deletions(-) create mode 100644 googletest/test/googletest-death-test-test.cc create mode 100755 googletest/test/googletest-uninitialized-test.py create mode 100644 googletest/test/googletest-uninitialized-test_.cc delete mode 100644 googletest/test/gtest-death-test_test.cc delete mode 100755 googletest/test/gtest_uninitialized_test.py diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 360ce26..780b278 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -56,6 +56,7 @@ cc_test( srcs = glob( include = [ "gtest-*.cc", + "googletest-*.cc", "*.h", "googletest/include/gtest/**/*.h", ], @@ -68,6 +69,17 @@ cc_test( "gtest-listener_test.cc", "gtest-unittest-api_test.cc", "gtest-param-test_test.cc", + "googletest-catch-exceptions-test_.cc", + "googletest-color-test_.cc", + "googletest-env-var-test_.cc", + "googletest-filter-unittest_.cc", + "googletest-break-on-failure-unittest_.cc", + "googletest-listener-test.cc", + "googletest-output-test_.cc", + "googletest-list-tests-unittest_.cc", + "googletest-shuffle-test_.cc", + "googletest-uninitialized-test_.cc", + ], ) + select({ "//:windows": [], @@ -98,6 +110,14 @@ cc_test( ) +# Tests death tests. +cc_test( + name = "googletest-death-test-test", + size = "medium", + srcs = ["googletest-death-test-test.cc"], + deps = ["//:gtest_main"], +) + cc_test( name = "gtest_test_macro_stack_footprint_test", size = "small", @@ -399,17 +419,17 @@ py_test( ) cc_binary( - name = "gtest_uninitialized_test_", + name = "googletest-uninitialized-test_", testonly = 1, - srcs = ["gtest_uninitialized_test_.cc"], + srcs = ["googletest-uninitialized-test_.cc"], deps = ["//:gtest"], ) py_test( - name = "gtest_uninitialized_test", + name = "googletest-uninitialized-test", size = "medium", - srcs = ["gtest_uninitialized_test.py"], - data = [":gtest_uninitialized_test_"], + srcs = ["googletest-uninitialized-test.py"], + data = ["googletest-uninitialized-test_"], deps = [":gtest_test_utils"], ) diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc new file mode 100644 index 0000000..37261cb --- /dev/null +++ b/googletest/test/googletest-death-test-test.cc @@ -0,0 +1,1424 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// Tests for death tests. + +#include "gtest/gtest-death-test.h" +#include "gtest/gtest.h" +#include "gtest/internal/gtest-filepath.h" + +using testing::internal::AlwaysFalse; +using testing::internal::AlwaysTrue; + +#if GTEST_HAS_DEATH_TEST + +# if GTEST_OS_WINDOWS +# include // For chdir(). +# else +# include +# include // For waitpid. +# endif // GTEST_OS_WINDOWS + +# include +# include +# include + +# if GTEST_OS_LINUX +# include +# endif // GTEST_OS_LINUX + +# include "gtest/gtest-spi.h" +# include "src/gtest-internal-inl.h" + +namespace posix = ::testing::internal::posix; + +using testing::Message; +using testing::internal::DeathTest; +using testing::internal::DeathTestFactory; +using testing::internal::FilePath; +using testing::internal::GetLastErrnoDescription; +using testing::internal::GetUnitTestImpl; +using testing::internal::InDeathTestChild; +using testing::internal::ParseNaturalNumber; + +namespace testing { +namespace internal { + +// A helper class whose objects replace the death test factory for a +// single UnitTest object during their lifetimes. +class ReplaceDeathTestFactory { + public: + explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory) + : unit_test_impl_(GetUnitTestImpl()) { + old_factory_ = unit_test_impl_->death_test_factory_.release(); + unit_test_impl_->death_test_factory_.reset(new_factory); + } + + ~ReplaceDeathTestFactory() { + unit_test_impl_->death_test_factory_.release(); + unit_test_impl_->death_test_factory_.reset(old_factory_); + } + private: + // Prevents copying ReplaceDeathTestFactory objects. + ReplaceDeathTestFactory(const ReplaceDeathTestFactory&); + void operator=(const ReplaceDeathTestFactory&); + + UnitTestImpl* unit_test_impl_; + DeathTestFactory* old_factory_; +}; + +} // namespace internal +} // namespace testing + +void DieWithMessage(const ::std::string& message) { + fprintf(stderr, "%s", message.c_str()); + fflush(stderr); // Make sure the text is printed before the process exits. + + // We call _exit() instead of exit(), as the former is a direct + // system call and thus safer in the presence of threads. exit() + // will invoke user-defined exit-hooks, which may do dangerous + // things that conflict with death tests. + // + // Some compilers can recognize that _exit() never returns and issue the + // 'unreachable code' warning for code following this function, unless + // fooled by a fake condition. + if (AlwaysTrue()) + _exit(1); +} + +void DieInside(const ::std::string& function) { + DieWithMessage("death inside " + function + "()."); +} + +// Tests that death tests work. + +class TestForDeathTest : public testing::Test { + protected: + TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {} + + virtual ~TestForDeathTest() { + posix::ChDir(original_dir_.c_str()); + } + + // A static member function that's expected to die. + static void StaticMemberFunction() { DieInside("StaticMemberFunction"); } + + // A method of the test fixture that may die. + void MemberFunction() { + if (should_die_) + DieInside("MemberFunction"); + } + + // True iff MemberFunction() should die. + bool should_die_; + const FilePath original_dir_; +}; + +// A class with a member function that may die. +class MayDie { + public: + explicit MayDie(bool should_die) : should_die_(should_die) {} + + // A member function that may die. + void MemberFunction() const { + if (should_die_) + DieInside("MayDie::MemberFunction"); + } + + private: + // True iff MemberFunction() should die. + bool should_die_; +}; + +// A global function that's expected to die. +void GlobalFunction() { DieInside("GlobalFunction"); } + +// A non-void function that's expected to die. +int NonVoidFunction() { + DieInside("NonVoidFunction"); + return 1; +} + +// A unary function that may die. +void DieIf(bool should_die) { + if (should_die) + DieInside("DieIf"); +} + +// A binary function that may die. +bool DieIfLessThan(int x, int y) { + if (x < y) { + DieInside("DieIfLessThan"); + } + return true; +} + +// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture. +void DeathTestSubroutine() { + EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction"); + ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction"); +} + +// Death in dbg, not opt. +int DieInDebugElse12(int* sideeffect) { + if (sideeffect) *sideeffect = 12; + +# ifndef NDEBUG + + DieInside("DieInDebugElse12"); + +# endif // NDEBUG + + return 12; +} + +# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA + +// Tests the ExitedWithCode predicate. +TEST(ExitStatusPredicateTest, ExitedWithCode) { + // On Windows, the process's exit code is the same as its exit status, + // so the predicate just compares the its input with its parameter. + EXPECT_TRUE(testing::ExitedWithCode(0)(0)); + EXPECT_TRUE(testing::ExitedWithCode(1)(1)); + EXPECT_TRUE(testing::ExitedWithCode(42)(42)); + EXPECT_FALSE(testing::ExitedWithCode(0)(1)); + EXPECT_FALSE(testing::ExitedWithCode(1)(0)); +} + +# else + +// Returns the exit status of a process that calls _exit(2) with a +// given exit code. This is a helper function for the +// ExitStatusPredicateTest test suite. +static int NormalExitStatus(int exit_code) { + pid_t child_pid = fork(); + if (child_pid == 0) { + _exit(exit_code); + } + int status; + waitpid(child_pid, &status, 0); + return status; +} + +// Returns the exit status of a process that raises a given signal. +// If the signal does not cause the process to die, then it returns +// instead the exit status of a process that exits normally with exit +// code 1. This is a helper function for the ExitStatusPredicateTest +// test suite. +static int KilledExitStatus(int signum) { + pid_t child_pid = fork(); + if (child_pid == 0) { + raise(signum); + _exit(1); + } + int status; + waitpid(child_pid, &status, 0); + return status; +} + +// Tests the ExitedWithCode predicate. +TEST(ExitStatusPredicateTest, ExitedWithCode) { + const int status0 = NormalExitStatus(0); + const int status1 = NormalExitStatus(1); + const int status42 = NormalExitStatus(42); + const testing::ExitedWithCode pred0(0); + const testing::ExitedWithCode pred1(1); + const testing::ExitedWithCode pred42(42); + EXPECT_PRED1(pred0, status0); + EXPECT_PRED1(pred1, status1); + EXPECT_PRED1(pred42, status42); + EXPECT_FALSE(pred0(status1)); + EXPECT_FALSE(pred42(status0)); + EXPECT_FALSE(pred1(status42)); +} + +// Tests the KilledBySignal predicate. +TEST(ExitStatusPredicateTest, KilledBySignal) { + const int status_segv = KilledExitStatus(SIGSEGV); + const int status_kill = KilledExitStatus(SIGKILL); + const testing::KilledBySignal pred_segv(SIGSEGV); + const testing::KilledBySignal pred_kill(SIGKILL); + EXPECT_PRED1(pred_segv, status_segv); + EXPECT_PRED1(pred_kill, status_kill); + EXPECT_FALSE(pred_segv(status_kill)); + EXPECT_FALSE(pred_kill(status_segv)); +} + +# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA + +// Tests that the death test macros expand to code which may or may not +// be followed by operator<<, and that in either case the complete text +// comprises only a single C++ statement. +TEST_F(TestForDeathTest, SingleStatement) { + if (AlwaysFalse()) + // This would fail if executed; this is a compilation test only + ASSERT_DEATH(return, ""); + + if (AlwaysTrue()) + EXPECT_DEATH(_exit(1), ""); + else + // This empty "else" branch is meant to ensure that EXPECT_DEATH + // doesn't expand into an "if" statement without an "else" + ; + + if (AlwaysFalse()) + ASSERT_DEATH(return, "") << "did not die"; + + if (AlwaysFalse()) + ; + else + EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3; +} + +void DieWithEmbeddedNul() { + fprintf(stderr, "Hello%cmy null world.\n", '\0'); + fflush(stderr); + _exit(1); +} + +# if GTEST_USES_PCRE + +// Tests that EXPECT_DEATH and ASSERT_DEATH work when the error +// message has a NUL character in it. +TEST_F(TestForDeathTest, EmbeddedNulInMessage) { + EXPECT_DEATH(DieWithEmbeddedNul(), "my null world"); + ASSERT_DEATH(DieWithEmbeddedNul(), "my null world"); +} + +# endif // GTEST_USES_PCRE + +// Tests that death test macros expand to code which interacts well with switch +// statements. +TEST_F(TestForDeathTest, SwitchStatement) { + // Microsoft compiler usually complains about switch statements without + // case labels. We suppress that warning for this test. + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) + + switch (0) + default: + ASSERT_DEATH(_exit(1), "") << "exit in default switch handler"; + + switch (0) + case 0: + EXPECT_DEATH(_exit(1), "") << "exit in switch case"; + + GTEST_DISABLE_MSC_WARNINGS_POP_() +} + +// Tests that a static member function can be used in a "fast" style +// death test. +TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) { + testing::GTEST_FLAG(death_test_style) = "fast"; + ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember"); +} + +// Tests that a method of the test fixture can be used in a "fast" +// style death test. +TEST_F(TestForDeathTest, MemberFunctionFastStyle) { + testing::GTEST_FLAG(death_test_style) = "fast"; + should_die_ = true; + EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction"); +} + +void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); } + +// Tests that death tests work even if the current directory has been +// changed. +TEST_F(TestForDeathTest, FastDeathTestInChangedDir) { + testing::GTEST_FLAG(death_test_style) = "fast"; + + ChangeToRootDir(); + EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); + + ChangeToRootDir(); + ASSERT_DEATH(_exit(1), ""); +} + +# if GTEST_OS_LINUX +void SigprofAction(int, siginfo_t*, void*) { /* no op */ } + +// Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms). +void SetSigprofActionAndTimer() { + struct itimerval timer; + timer.it_interval.tv_sec = 0; + timer.it_interval.tv_usec = 1; + timer.it_value = timer.it_interval; + ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL)); + struct sigaction signal_action; + memset(&signal_action, 0, sizeof(signal_action)); + sigemptyset(&signal_action.sa_mask); + signal_action.sa_sigaction = SigprofAction; + signal_action.sa_flags = SA_RESTART | SA_SIGINFO; + ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, NULL)); +} + +// Disables ITIMER_PROF timer and ignores SIGPROF signal. +void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) { + struct itimerval timer; + timer.it_interval.tv_sec = 0; + timer.it_interval.tv_usec = 0; + timer.it_value = timer.it_interval; + ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL)); + struct sigaction signal_action; + memset(&signal_action, 0, sizeof(signal_action)); + sigemptyset(&signal_action.sa_mask); + signal_action.sa_handler = SIG_IGN; + ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action)); +} + +// Tests that death tests work when SIGPROF handler and timer are set. +TEST_F(TestForDeathTest, FastSigprofActionSet) { + testing::GTEST_FLAG(death_test_style) = "fast"; + SetSigprofActionAndTimer(); + EXPECT_DEATH(_exit(1), ""); + struct sigaction old_signal_action; + DisableSigprofActionAndTimer(&old_signal_action); + EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction); +} + +TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) { + testing::GTEST_FLAG(death_test_style) = "threadsafe"; + SetSigprofActionAndTimer(); + EXPECT_DEATH(_exit(1), ""); + struct sigaction old_signal_action; + DisableSigprofActionAndTimer(&old_signal_action); + EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction); +} +# endif // GTEST_OS_LINUX + +// Repeats a representative sample of death tests in the "threadsafe" style: + +TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) { + testing::GTEST_FLAG(death_test_style) = "threadsafe"; + ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember"); +} + +TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) { + testing::GTEST_FLAG(death_test_style) = "threadsafe"; + should_die_ = true; + EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction"); +} + +TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) { + testing::GTEST_FLAG(death_test_style) = "threadsafe"; + + for (int i = 0; i < 3; ++i) + EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i; +} + +TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) { + testing::GTEST_FLAG(death_test_style) = "threadsafe"; + + ChangeToRootDir(); + EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); + + ChangeToRootDir(); + ASSERT_DEATH(_exit(1), ""); +} + +TEST_F(TestForDeathTest, MixedStyles) { + testing::GTEST_FLAG(death_test_style) = "threadsafe"; + EXPECT_DEATH(_exit(1), ""); + testing::GTEST_FLAG(death_test_style) = "fast"; + EXPECT_DEATH(_exit(1), ""); +} + +# if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD + +namespace { + +bool pthread_flag; + +void SetPthreadFlag() { + pthread_flag = true; +} + +} // namespace + +TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { + if (!testing::GTEST_FLAG(death_test_use_fork)) { + testing::GTEST_FLAG(death_test_style) = "threadsafe"; + pthread_flag = false; + ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL)); + ASSERT_DEATH(_exit(1), ""); + ASSERT_FALSE(pthread_flag); + } +} + +# endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD + +// Tests that a method of another class can be used in a death test. +TEST_F(TestForDeathTest, MethodOfAnotherClass) { + const MayDie x(true); + ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction"); +} + +// Tests that a global function can be used in a death test. +TEST_F(TestForDeathTest, GlobalFunction) { + EXPECT_DEATH(GlobalFunction(), "GlobalFunction"); +} + +// Tests that any value convertible to an RE works as a second +// argument to EXPECT_DEATH. +TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { + static const char regex_c_str[] = "GlobalFunction"; + EXPECT_DEATH(GlobalFunction(), regex_c_str); + + const testing::internal::RE regex(regex_c_str); + EXPECT_DEATH(GlobalFunction(), regex); + +# if GTEST_HAS_GLOBAL_STRING + + const ::string regex_str(regex_c_str); + EXPECT_DEATH(GlobalFunction(), regex_str); + +# endif // GTEST_HAS_GLOBAL_STRING + +# if !GTEST_USES_PCRE + + const ::std::string regex_std_str(regex_c_str); + EXPECT_DEATH(GlobalFunction(), regex_std_str); + +# endif // !GTEST_USES_PCRE +} + +// Tests that a non-void function can be used in a death test. +TEST_F(TestForDeathTest, NonVoidFunction) { + ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction"); +} + +// Tests that functions that take parameter(s) can be used in a death test. +TEST_F(TestForDeathTest, FunctionWithParameter) { + EXPECT_DEATH(DieIf(true), "DieIf\\(\\)"); + EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan"); +} + +// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture. +TEST_F(TestForDeathTest, OutsideFixture) { + DeathTestSubroutine(); +} + +// Tests that death tests can be done inside a loop. +TEST_F(TestForDeathTest, InsideLoop) { + for (int i = 0; i < 5; i++) { + EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i; + } +} + +// Tests that a compound statement can be used in a death test. +TEST_F(TestForDeathTest, CompoundStatement) { + EXPECT_DEATH({ // NOLINT + const int x = 2; + const int y = x + 1; + DieIfLessThan(x, y); + }, + "DieIfLessThan"); +} + +// Tests that code that doesn't die causes a death test to fail. +TEST_F(TestForDeathTest, DoesNotDie) { + EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), + "failed to die"); +} + +// Tests that a death test fails when the error message isn't expected. +TEST_F(TestForDeathTest, ErrorMessageMismatch) { + EXPECT_NONFATAL_FAILURE({ // NOLINT + EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message."; + }, "died but not with expected error"); +} + +// On exit, *aborted will be true iff the EXPECT_DEATH() statement +// aborted the function. +void ExpectDeathTestHelper(bool* aborted) { + *aborted = true; + EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. + *aborted = false; +} + +// Tests that EXPECT_DEATH doesn't abort the test on failure. +TEST_F(TestForDeathTest, EXPECT_DEATH) { + bool aborted = true; + EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), + "failed to die"); + EXPECT_FALSE(aborted); +} + +// Tests that ASSERT_DEATH does abort the test on failure. +TEST_F(TestForDeathTest, ASSERT_DEATH) { + static bool aborted; + EXPECT_FATAL_FAILURE({ // NOLINT + aborted = true; + ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. + aborted = false; + }, "failed to die"); + EXPECT_TRUE(aborted); +} + +// Tests that EXPECT_DEATH evaluates the arguments exactly once. +TEST_F(TestForDeathTest, SingleEvaluation) { + int x = 3; + EXPECT_DEATH(DieIf((++x) == 4), "DieIf"); + + const char* regex = "DieIf"; + const char* regex_save = regex; + EXPECT_DEATH(DieIfLessThan(3, 4), regex++); + EXPECT_EQ(regex_save + 1, regex); +} + +// Tests that run-away death tests are reported as failures. +TEST_F(TestForDeathTest, RunawayIsFailure) { + EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast(0), "Foo"), + "failed to die."); +} + +// Tests that death tests report executing 'return' in the statement as +// failure. +TEST_F(TestForDeathTest, ReturnIsFailure) { + EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"), + "illegal return in test statement."); +} + +// Tests that EXPECT_DEBUG_DEATH works as expected, that is, you can stream a +// message to it, and in debug mode it: +// 1. Asserts on death. +// 2. Has no side effect. +// +// And in opt mode, it: +// 1. Has side effects but does not assert. +TEST_F(TestForDeathTest, TestExpectDebugDeath) { + int sideeffect = 0; + + // Put the regex in a local variable to make sure we don't get an "unused" + // warning in opt mode. + const char* regex = "death.*DieInDebugElse12"; + + EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex) + << "Must accept a streamed message"; + +# ifdef NDEBUG + + // Checks that the assignment occurs in opt mode (sideeffect). + EXPECT_EQ(12, sideeffect); + +# else + + // Checks that the assignment does not occur in dbg mode (no sideeffect). + EXPECT_EQ(0, sideeffect); + +# endif +} + +// Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a +// message to it, and in debug mode it: +// 1. Asserts on death. +// 2. Has no side effect. +// +// And in opt mode, it: +// 1. Has side effects but does not assert. +TEST_F(TestForDeathTest, TestAssertDebugDeath) { + int sideeffect = 0; + + ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12") + << "Must accept a streamed message"; + +# ifdef NDEBUG + + // Checks that the assignment occurs in opt mode (sideeffect). + EXPECT_EQ(12, sideeffect); + +# else + + // Checks that the assignment does not occur in dbg mode (no sideeffect). + EXPECT_EQ(0, sideeffect); + +# endif +} + +# ifndef NDEBUG + +void ExpectDebugDeathHelper(bool* aborted) { + *aborted = true; + EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail."; + *aborted = false; +} + +# if GTEST_OS_WINDOWS +TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { + 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; + abort(); + }, ""); +} +# endif // GTEST_OS_WINDOWS + +// Tests that EXPECT_DEBUG_DEATH in debug mode does not abort +// the function. +TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) { + bool aborted = true; + EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), ""); + EXPECT_FALSE(aborted); +} + +void AssertDebugDeathHelper(bool* aborted) { + *aborted = true; + GTEST_LOG_(INFO) << "Before ASSERT_DEBUG_DEATH"; + ASSERT_DEBUG_DEATH(GTEST_LOG_(INFO) << "In ASSERT_DEBUG_DEATH"; return, "") + << "This is expected to fail."; + GTEST_LOG_(INFO) << "After ASSERT_DEBUG_DEATH"; + *aborted = false; +} + +// Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on +// failure. +TEST_F(TestForDeathTest, AssertDebugDeathAborts) { + static bool aborted; + aborted = false; + EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); + EXPECT_TRUE(aborted); +} + +TEST_F(TestForDeathTest, AssertDebugDeathAborts2) { + static bool aborted; + aborted = false; + EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); + EXPECT_TRUE(aborted); +} + +TEST_F(TestForDeathTest, AssertDebugDeathAborts3) { + static bool aborted; + aborted = false; + EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); + EXPECT_TRUE(aborted); +} + +TEST_F(TestForDeathTest, AssertDebugDeathAborts4) { + static bool aborted; + aborted = false; + EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); + EXPECT_TRUE(aborted); +} + +TEST_F(TestForDeathTest, AssertDebugDeathAborts5) { + static bool aborted; + aborted = false; + EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); + EXPECT_TRUE(aborted); +} + +TEST_F(TestForDeathTest, AssertDebugDeathAborts6) { + static bool aborted; + aborted = false; + EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); + EXPECT_TRUE(aborted); +} + +TEST_F(TestForDeathTest, AssertDebugDeathAborts7) { + static bool aborted; + aborted = false; + EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); + EXPECT_TRUE(aborted); +} + +TEST_F(TestForDeathTest, AssertDebugDeathAborts8) { + static bool aborted; + aborted = false; + EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); + EXPECT_TRUE(aborted); +} + +TEST_F(TestForDeathTest, AssertDebugDeathAborts9) { + static bool aborted; + aborted = false; + EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); + EXPECT_TRUE(aborted); +} + +TEST_F(TestForDeathTest, AssertDebugDeathAborts10) { + static bool aborted; + aborted = false; + EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); + EXPECT_TRUE(aborted); +} + +# endif // _NDEBUG + +// Tests the *_EXIT family of macros, using a variety of predicates. +static void TestExitMacros() { + EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); + ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), ""); + +# if GTEST_OS_WINDOWS + + // Of all signals effects on the process exit code, only those of SIGABRT + // are documented on Windows. + // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx. + EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar"; + +# elif !GTEST_OS_FUCHSIA + + // Fuchsia has no unix signals. + EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo"; + ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar"; + + EXPECT_FATAL_FAILURE({ // NOLINT + ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "") + << "This failure is expected, too."; + }, "This failure is expected, too."); + +# endif // GTEST_OS_WINDOWS + + EXPECT_NONFATAL_FAILURE({ // NOLINT + EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "") + << "This failure is expected."; + }, "This failure is expected."); +} + +TEST_F(TestForDeathTest, ExitMacros) { + TestExitMacros(); +} + +TEST_F(TestForDeathTest, ExitMacrosUsingFork) { + testing::GTEST_FLAG(death_test_use_fork) = true; + TestExitMacros(); +} + +TEST_F(TestForDeathTest, InvalidStyle) { + testing::GTEST_FLAG(death_test_style) = "rococo"; + EXPECT_NONFATAL_FAILURE({ // NOLINT + EXPECT_DEATH(_exit(0), "") << "This failure is expected."; + }, "This failure is expected."); +} + +TEST_F(TestForDeathTest, DeathTestFailedOutput) { + testing::GTEST_FLAG(death_test_style) = "fast"; + EXPECT_NONFATAL_FAILURE( + EXPECT_DEATH(DieWithMessage("death\n"), + "expected message"), + "Actual msg:\n" + "[ DEATH ] death\n"); +} + +TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) { + testing::GTEST_FLAG(death_test_style) = "fast"; + EXPECT_NONFATAL_FAILURE( + EXPECT_DEATH({ + fprintf(stderr, "returning\n"); + fflush(stderr); + return; + }, ""), + " Result: illegal return in test statement.\n" + " Error msg:\n" + "[ DEATH ] returning\n"); +} + +TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) { + testing::GTEST_FLAG(death_test_style) = "fast"; + EXPECT_NONFATAL_FAILURE( + EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"), + testing::ExitedWithCode(3), + "expected message"), + " Result: died but not with expected exit code:\n" + " Exited with exit status 1\n" + "Actual msg:\n" + "[ DEATH ] exiting with rc 1\n"); +} + +TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) { + testing::GTEST_FLAG(death_test_style) = "fast"; + EXPECT_NONFATAL_FAILURE( + EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"), + "line 1\nxyz\nline 3\n"), + "Actual msg:\n" + "[ DEATH ] line 1\n" + "[ DEATH ] line 2\n" + "[ DEATH ] line 3\n"); +} + +TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) { + testing::GTEST_FLAG(death_test_style) = "fast"; + EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"), + "line 1\nline 2\nline 3\n"); +} + +// A DeathTestFactory that returns MockDeathTests. +class MockDeathTestFactory : public DeathTestFactory { + public: + MockDeathTestFactory(); + virtual bool Create(const char* statement, + const ::testing::internal::RE* regex, + const char* file, int line, DeathTest** test); + + // Sets the parameters for subsequent calls to Create. + void SetParameters(bool create, DeathTest::TestRole role, + int status, bool passed); + + // Accessors. + int AssumeRoleCalls() const { return assume_role_calls_; } + int WaitCalls() const { return wait_calls_; } + size_t PassedCalls() const { return passed_args_.size(); } + bool PassedArgument(int n) const { return passed_args_[n]; } + size_t AbortCalls() const { return abort_args_.size(); } + DeathTest::AbortReason AbortArgument(int n) const { + return abort_args_[n]; + } + bool TestDeleted() const { return test_deleted_; } + + private: + friend class MockDeathTest; + // If true, Create will return a MockDeathTest; otherwise it returns + // NULL. + bool create_; + // The value a MockDeathTest will return from its AssumeRole method. + DeathTest::TestRole role_; + // The value a MockDeathTest will return from its Wait method. + int status_; + // The value a MockDeathTest will return from its Passed method. + bool passed_; + + // Number of times AssumeRole was called. + int assume_role_calls_; + // Number of times Wait was called. + int wait_calls_; + // The arguments to the calls to Passed since the last call to + // SetParameters. + std::vector passed_args_; + // The arguments to the calls to Abort since the last call to + // SetParameters. + std::vector abort_args_; + // True if the last MockDeathTest returned by Create has been + // deleted. + bool test_deleted_; +}; + + +// A DeathTest implementation useful in testing. It returns values set +// at its creation from its various inherited DeathTest methods, and +// reports calls to those methods to its parent MockDeathTestFactory +// object. +class MockDeathTest : public DeathTest { + public: + MockDeathTest(MockDeathTestFactory *parent, + TestRole role, int status, bool passed) : + parent_(parent), role_(role), status_(status), passed_(passed) { + } + virtual ~MockDeathTest() { + parent_->test_deleted_ = true; + } + virtual TestRole AssumeRole() { + ++parent_->assume_role_calls_; + return role_; + } + virtual int Wait() { + ++parent_->wait_calls_; + return status_; + } + virtual bool Passed(bool exit_status_ok) { + parent_->passed_args_.push_back(exit_status_ok); + return passed_; + } + virtual void Abort(AbortReason reason) { + parent_->abort_args_.push_back(reason); + } + + private: + MockDeathTestFactory* const parent_; + const TestRole role_; + const int status_; + const bool passed_; +}; + + +// MockDeathTestFactory constructor. +MockDeathTestFactory::MockDeathTestFactory() + : create_(true), + role_(DeathTest::OVERSEE_TEST), + status_(0), + passed_(true), + assume_role_calls_(0), + wait_calls_(0), + passed_args_(), + abort_args_() { +} + + +// Sets the parameters for subsequent calls to Create. +void MockDeathTestFactory::SetParameters(bool create, + DeathTest::TestRole role, + int status, bool passed) { + create_ = create; + role_ = role; + status_ = status; + passed_ = passed; + + assume_role_calls_ = 0; + wait_calls_ = 0; + passed_args_.clear(); + abort_args_.clear(); +} + + +// Sets test to NULL (if create_ is false) or to the address of a new +// MockDeathTest object with parameters taken from the last call +// to SetParameters (if create_ is true). Always returns true. +bool MockDeathTestFactory::Create(const char* /*statement*/, + const ::testing::internal::RE* /*regex*/, + const char* /*file*/, + int /*line*/, + DeathTest** test) { + test_deleted_ = false; + if (create_) { + *test = new MockDeathTest(this, role_, status_, passed_); + } else { + *test = NULL; + } + return true; +} + +// A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro. +// It installs a MockDeathTestFactory that is used for the duration +// of the test case. +class MacroLogicDeathTest : public testing::Test { + protected: + static testing::internal::ReplaceDeathTestFactory* replacer_; + static MockDeathTestFactory* factory_; + + static void SetUpTestCase() { + factory_ = new MockDeathTestFactory; + replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_); + } + + static void TearDownTestCase() { + delete replacer_; + replacer_ = NULL; + delete factory_; + factory_ = NULL; + } + + // Runs a death test that breaks the rules by returning. Such a death + // test cannot be run directly from a test routine that uses a + // MockDeathTest, or the remainder of the routine will not be executed. + static void RunReturningDeathTest(bool* flag) { + ASSERT_DEATH({ // NOLINT + *flag = true; + return; + }, ""); + } +}; + +testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_ + = NULL; +MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL; + + +// Test that nothing happens when the factory doesn't return a DeathTest: +TEST_F(MacroLogicDeathTest, NothingHappens) { + bool flag = false; + factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true); + EXPECT_DEATH(flag = true, ""); + EXPECT_FALSE(flag); + EXPECT_EQ(0, factory_->AssumeRoleCalls()); + EXPECT_EQ(0, factory_->WaitCalls()); + EXPECT_EQ(0U, factory_->PassedCalls()); + EXPECT_EQ(0U, factory_->AbortCalls()); + EXPECT_FALSE(factory_->TestDeleted()); +} + +// Test that the parent process doesn't run the death test code, +// and that the Passed method returns false when the (simulated) +// child process exits with status 0: +TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) { + bool flag = false; + factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true); + EXPECT_DEATH(flag = true, ""); + EXPECT_FALSE(flag); + EXPECT_EQ(1, factory_->AssumeRoleCalls()); + EXPECT_EQ(1, factory_->WaitCalls()); + ASSERT_EQ(1U, factory_->PassedCalls()); + EXPECT_FALSE(factory_->PassedArgument(0)); + EXPECT_EQ(0U, factory_->AbortCalls()); + EXPECT_TRUE(factory_->TestDeleted()); +} + +// Tests that the Passed method was given the argument "true" when +// the (simulated) child process exits with status 1: +TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) { + bool flag = false; + factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true); + EXPECT_DEATH(flag = true, ""); + EXPECT_FALSE(flag); + EXPECT_EQ(1, factory_->AssumeRoleCalls()); + EXPECT_EQ(1, factory_->WaitCalls()); + ASSERT_EQ(1U, factory_->PassedCalls()); + EXPECT_TRUE(factory_->PassedArgument(0)); + EXPECT_EQ(0U, factory_->AbortCalls()); + EXPECT_TRUE(factory_->TestDeleted()); +} + +// Tests that the (simulated) child process executes the death test +// code, and is aborted with the correct AbortReason if it +// executes a return statement. +TEST_F(MacroLogicDeathTest, ChildPerformsReturn) { + bool flag = false; + factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true); + RunReturningDeathTest(&flag); + EXPECT_TRUE(flag); + EXPECT_EQ(1, factory_->AssumeRoleCalls()); + EXPECT_EQ(0, factory_->WaitCalls()); + EXPECT_EQ(0U, factory_->PassedCalls()); + EXPECT_EQ(1U, factory_->AbortCalls()); + EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT, + factory_->AbortArgument(0)); + EXPECT_TRUE(factory_->TestDeleted()); +} + +// Tests that the (simulated) child process is aborted with the +// correct AbortReason if it does not die. +TEST_F(MacroLogicDeathTest, ChildDoesNotDie) { + bool flag = false; + factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true); + EXPECT_DEATH(flag = true, ""); + EXPECT_TRUE(flag); + EXPECT_EQ(1, factory_->AssumeRoleCalls()); + EXPECT_EQ(0, factory_->WaitCalls()); + EXPECT_EQ(0U, factory_->PassedCalls()); + // This time there are two calls to Abort: one since the test didn't + // die, and another from the ReturnSentinel when it's destroyed. The + // sentinel normally isn't destroyed if a test doesn't die, since + // _exit(2) is called in that case by ForkingDeathTest, but not by + // our MockDeathTest. + ASSERT_EQ(2U, factory_->AbortCalls()); + EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, + factory_->AbortArgument(0)); + EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT, + factory_->AbortArgument(1)); + EXPECT_TRUE(factory_->TestDeleted()); +} + +// Tests that a successful death test does not register a successful +// test part. +TEST(SuccessRegistrationDeathTest, NoSuccessPart) { + EXPECT_DEATH(_exit(1), ""); + EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); +} + +TEST(StreamingAssertionsDeathTest, DeathTest) { + EXPECT_DEATH(_exit(1), "") << "unexpected failure"; + ASSERT_DEATH(_exit(1), "") << "unexpected failure"; + EXPECT_NONFATAL_FAILURE({ // NOLINT + EXPECT_DEATH(_exit(0), "") << "expected failure"; + }, "expected failure"); + EXPECT_FATAL_FAILURE({ // NOLINT + ASSERT_DEATH(_exit(0), "") << "expected failure"; + }, "expected failure"); +} + +// Tests that GetLastErrnoDescription returns an empty string when the +// last error is 0 and non-empty string when it is non-zero. +TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) { + errno = ENOENT; + EXPECT_STRNE("", GetLastErrnoDescription().c_str()); + errno = 0; + EXPECT_STREQ("", GetLastErrnoDescription().c_str()); +} + +# if GTEST_OS_WINDOWS +TEST(AutoHandleTest, AutoHandleWorks) { + HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); + ASSERT_NE(INVALID_HANDLE_VALUE, handle); + + // Tests that the AutoHandle is correctly initialized with a handle. + testing::internal::AutoHandle auto_handle(handle); + EXPECT_EQ(handle, auto_handle.Get()); + + // Tests that Reset assigns INVALID_HANDLE_VALUE. + // Note that this cannot verify whether the original handle is closed. + auto_handle.Reset(); + EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get()); + + // Tests that Reset assigns the new handle. + // Note that this cannot verify whether the original handle is closed. + handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); + ASSERT_NE(INVALID_HANDLE_VALUE, handle); + auto_handle.Reset(handle); + EXPECT_EQ(handle, auto_handle.Get()); + + // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default. + testing::internal::AutoHandle auto_handle2; + EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get()); +} +# endif // GTEST_OS_WINDOWS + +# if GTEST_OS_WINDOWS +typedef unsigned __int64 BiggestParsable; +typedef signed __int64 BiggestSignedParsable; +# else +typedef unsigned long long BiggestParsable; +typedef signed long long BiggestSignedParsable; +# endif // GTEST_OS_WINDOWS + +// We cannot use std::numeric_limits::max() as it clashes with the +// max() macro defined by . +const BiggestParsable kBiggestParsableMax = ULLONG_MAX; +const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX; + +TEST(ParseNaturalNumberTest, RejectsInvalidFormat) { + BiggestParsable result = 0; + + // Rejects non-numbers. + EXPECT_FALSE(ParseNaturalNumber("non-number string", &result)); + + // Rejects numbers with whitespace prefix. + EXPECT_FALSE(ParseNaturalNumber(" 123", &result)); + + // Rejects negative numbers. + EXPECT_FALSE(ParseNaturalNumber("-123", &result)); + + // Rejects numbers starting with a plus sign. + EXPECT_FALSE(ParseNaturalNumber("+123", &result)); + errno = 0; +} + +TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) { + BiggestParsable result = 0; + + EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result)); + + signed char char_result = 0; + EXPECT_FALSE(ParseNaturalNumber("200", &char_result)); + errno = 0; +} + +TEST(ParseNaturalNumberTest, AcceptsValidNumbers) { + BiggestParsable result = 0; + + result = 0; + ASSERT_TRUE(ParseNaturalNumber("123", &result)); + EXPECT_EQ(123U, result); + + // Check 0 as an edge case. + result = 1; + ASSERT_TRUE(ParseNaturalNumber("0", &result)); + EXPECT_EQ(0U, result); + + result = 1; + ASSERT_TRUE(ParseNaturalNumber("00000", &result)); + EXPECT_EQ(0U, result); +} + +TEST(ParseNaturalNumberTest, AcceptsTypeLimits) { + Message msg; + msg << kBiggestParsableMax; + + BiggestParsable result = 0; + EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result)); + EXPECT_EQ(kBiggestParsableMax, result); + + Message msg2; + msg2 << kBiggestSignedParsableMax; + + BiggestSignedParsable signed_result = 0; + EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result)); + EXPECT_EQ(kBiggestSignedParsableMax, signed_result); + + Message msg3; + msg3 << INT_MAX; + + int int_result = 0; + EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result)); + EXPECT_EQ(INT_MAX, int_result); + + Message msg4; + msg4 << UINT_MAX; + + unsigned int uint_result = 0; + EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result)); + EXPECT_EQ(UINT_MAX, uint_result); +} + +TEST(ParseNaturalNumberTest, WorksForShorterIntegers) { + short short_result = 0; + ASSERT_TRUE(ParseNaturalNumber("123", &short_result)); + EXPECT_EQ(123, short_result); + + signed char char_result = 0; + ASSERT_TRUE(ParseNaturalNumber("123", &char_result)); + EXPECT_EQ(123, char_result); +} + +# if GTEST_OS_WINDOWS +TEST(EnvironmentTest, HandleFitsIntoSizeT) { + // TODO(vladl@google.com): Remove this test after this condition is verified + // in a static assertion in gtest-death-test.cc in the function + // GetStatusFileDescriptor. + ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t)); +} +# endif // GTEST_OS_WINDOWS + +// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger +// failures when death tests are available on the system. +TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) { + EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"), + "death inside CondDeathTestExpectMacro"); + ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"), + "death inside CondDeathTestAssertMacro"); + + // Empty statement will not crash, which must trigger a failure. + EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), ""); + EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), ""); +} + +TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) { + testing::GTEST_FLAG(death_test_style) = "fast"; + EXPECT_FALSE(InDeathTestChild()); + EXPECT_DEATH({ + fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); + fflush(stderr); + _exit(1); + }, "Inside"); +} + +TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) { + testing::GTEST_FLAG(death_test_style) = "threadsafe"; + EXPECT_FALSE(InDeathTestChild()); + EXPECT_DEATH({ + fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); + fflush(stderr); + _exit(1); + }, "Inside"); +} + +#else // !GTEST_HAS_DEATH_TEST follows + +using testing::internal::CaptureStderr; +using testing::internal::GetCapturedStderr; + +// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still +// defined but do not trigger failures when death tests are not available on +// the system. +TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) { + // Empty statement will not crash, but that should not trigger a failure + // when death tests are not supported. + CaptureStderr(); + EXPECT_DEATH_IF_SUPPORTED(;, ""); + std::string output = GetCapturedStderr(); + ASSERT_TRUE(NULL != strstr(output.c_str(), + "Death tests are not supported on this platform")); + ASSERT_TRUE(NULL != strstr(output.c_str(), ";")); + + // The streamed message should not be printed as there is no test failure. + CaptureStderr(); + EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; + output = GetCapturedStderr(); + ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message")); + + CaptureStderr(); + ASSERT_DEATH_IF_SUPPORTED(;, ""); // NOLINT + output = GetCapturedStderr(); + ASSERT_TRUE(NULL != strstr(output.c_str(), + "Death tests are not supported on this platform")); + ASSERT_TRUE(NULL != strstr(output.c_str(), ";")); + + CaptureStderr(); + ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; // NOLINT + output = GetCapturedStderr(); + ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message")); +} + +void FuncWithAssert(int* n) { + ASSERT_DEATH_IF_SUPPORTED(return;, ""); + (*n)++; +} + +// Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current +// function (as ASSERT_DEATH does) if death tests are not supported. +TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) { + int n = 0; + FuncWithAssert(&n); + EXPECT_EQ(1, n); +} + +#endif // !GTEST_HAS_DEATH_TEST + +// Tests that the death test macros expand to code which may or may not +// be followed by operator<<, and that in either case the complete text +// comprises only a single C++ statement. +// +// The syntax should work whether death tests are available or not. +TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) { + if (AlwaysFalse()) + // This would fail if executed; this is a compilation test only + ASSERT_DEATH_IF_SUPPORTED(return, ""); + + if (AlwaysTrue()) + EXPECT_DEATH_IF_SUPPORTED(_exit(1), ""); + else + // This empty "else" branch is meant to ensure that EXPECT_DEATH + // doesn't expand into an "if" statement without an "else" + ; // NOLINT + + if (AlwaysFalse()) + ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die"; + + if (AlwaysFalse()) + ; // NOLINT + else + EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3; +} + +// Tests that conditional death test macros expand to code which interacts +// well with switch statements. +TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) { + // Microsoft compiler usually complains about switch statements without + // case labels. We suppress that warning for this test. + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) + + switch (0) + default: + ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") + << "exit in default switch handler"; + + switch (0) + case 0: + EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case"; + + GTEST_DISABLE_MSC_WARNINGS_POP_() +} + +// Tests that a test case whose name ends with "DeathTest" works fine +// on Windows. +TEST(NotADeathTest, Test) { + SUCCEED(); +} diff --git a/googletest/test/googletest-uninitialized-test.py b/googletest/test/googletest-uninitialized-test.py new file mode 100755 index 0000000..e3df5fa --- /dev/null +++ b/googletest/test/googletest-uninitialized-test.py @@ -0,0 +1,69 @@ +#!/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. + +"""Verifies that Google Test warns the user when not initialized properly.""" + +__author__ = 'wan@google.com (Zhanyong Wan)' + +import gtest_test_utils + +COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-uninitialized-test_') + + +def Assert(condition): + if not condition: + raise AssertionError + + +def AssertEq(expected, actual): + if expected != actual: + print 'Expected: %s' % (expected,) + print ' Actual: %s' % (actual,) + raise AssertionError + + +def TestExitCodeAndOutput(command): + """Runs the given command and verifies its exit code and output.""" + + # Verifies that 'command' exits with code 1. + p = gtest_test_utils.Subprocess(command) + if p.exited and p.exit_code == 0: + Assert('IMPORTANT NOTICE' in p.output); + Assert('InitGoogleTest' in p.output) + + +class GTestUninitializedTest(gtest_test_utils.TestCase): + def testExitCodeAndOutput(self): + TestExitCodeAndOutput(COMMAND) + + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/googletest-uninitialized-test_.cc b/googletest/test/googletest-uninitialized-test_.cc new file mode 100644 index 0000000..2ba0e8b --- /dev/null +++ b/googletest/test/googletest-uninitialized-test_.cc @@ -0,0 +1,43 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +#include "gtest/gtest.h" + +TEST(DummyTest, Dummy) { + // This test doesn't verify anything. We just need it to create a + // realistic stage for testing the behavior of Google Test when + // RUN_ALL_TESTS() is called without + // testing::InitGoogleTest() being called first. +} + +int main() { + return RUN_ALL_TESTS(); +} diff --git a/googletest/test/gtest-death-test_test.cc b/googletest/test/gtest-death-test_test.cc deleted file mode 100644 index 37261cb..0000000 --- a/googletest/test/gtest-death-test_test.cc +++ /dev/null @@ -1,1424 +0,0 @@ -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) -// -// Tests for death tests. - -#include "gtest/gtest-death-test.h" -#include "gtest/gtest.h" -#include "gtest/internal/gtest-filepath.h" - -using testing::internal::AlwaysFalse; -using testing::internal::AlwaysTrue; - -#if GTEST_HAS_DEATH_TEST - -# if GTEST_OS_WINDOWS -# include // For chdir(). -# else -# include -# include // For waitpid. -# endif // GTEST_OS_WINDOWS - -# include -# include -# include - -# if GTEST_OS_LINUX -# include -# endif // GTEST_OS_LINUX - -# include "gtest/gtest-spi.h" -# include "src/gtest-internal-inl.h" - -namespace posix = ::testing::internal::posix; - -using testing::Message; -using testing::internal::DeathTest; -using testing::internal::DeathTestFactory; -using testing::internal::FilePath; -using testing::internal::GetLastErrnoDescription; -using testing::internal::GetUnitTestImpl; -using testing::internal::InDeathTestChild; -using testing::internal::ParseNaturalNumber; - -namespace testing { -namespace internal { - -// A helper class whose objects replace the death test factory for a -// single UnitTest object during their lifetimes. -class ReplaceDeathTestFactory { - public: - explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory) - : unit_test_impl_(GetUnitTestImpl()) { - old_factory_ = unit_test_impl_->death_test_factory_.release(); - unit_test_impl_->death_test_factory_.reset(new_factory); - } - - ~ReplaceDeathTestFactory() { - unit_test_impl_->death_test_factory_.release(); - unit_test_impl_->death_test_factory_.reset(old_factory_); - } - private: - // Prevents copying ReplaceDeathTestFactory objects. - ReplaceDeathTestFactory(const ReplaceDeathTestFactory&); - void operator=(const ReplaceDeathTestFactory&); - - UnitTestImpl* unit_test_impl_; - DeathTestFactory* old_factory_; -}; - -} // namespace internal -} // namespace testing - -void DieWithMessage(const ::std::string& message) { - fprintf(stderr, "%s", message.c_str()); - fflush(stderr); // Make sure the text is printed before the process exits. - - // We call _exit() instead of exit(), as the former is a direct - // system call and thus safer in the presence of threads. exit() - // will invoke user-defined exit-hooks, which may do dangerous - // things that conflict with death tests. - // - // Some compilers can recognize that _exit() never returns and issue the - // 'unreachable code' warning for code following this function, unless - // fooled by a fake condition. - if (AlwaysTrue()) - _exit(1); -} - -void DieInside(const ::std::string& function) { - DieWithMessage("death inside " + function + "()."); -} - -// Tests that death tests work. - -class TestForDeathTest : public testing::Test { - protected: - TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {} - - virtual ~TestForDeathTest() { - posix::ChDir(original_dir_.c_str()); - } - - // A static member function that's expected to die. - static void StaticMemberFunction() { DieInside("StaticMemberFunction"); } - - // A method of the test fixture that may die. - void MemberFunction() { - if (should_die_) - DieInside("MemberFunction"); - } - - // True iff MemberFunction() should die. - bool should_die_; - const FilePath original_dir_; -}; - -// A class with a member function that may die. -class MayDie { - public: - explicit MayDie(bool should_die) : should_die_(should_die) {} - - // A member function that may die. - void MemberFunction() const { - if (should_die_) - DieInside("MayDie::MemberFunction"); - } - - private: - // True iff MemberFunction() should die. - bool should_die_; -}; - -// A global function that's expected to die. -void GlobalFunction() { DieInside("GlobalFunction"); } - -// A non-void function that's expected to die. -int NonVoidFunction() { - DieInside("NonVoidFunction"); - return 1; -} - -// A unary function that may die. -void DieIf(bool should_die) { - if (should_die) - DieInside("DieIf"); -} - -// A binary function that may die. -bool DieIfLessThan(int x, int y) { - if (x < y) { - DieInside("DieIfLessThan"); - } - return true; -} - -// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture. -void DeathTestSubroutine() { - EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction"); - ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction"); -} - -// Death in dbg, not opt. -int DieInDebugElse12(int* sideeffect) { - if (sideeffect) *sideeffect = 12; - -# ifndef NDEBUG - - DieInside("DieInDebugElse12"); - -# endif // NDEBUG - - return 12; -} - -# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA - -// Tests the ExitedWithCode predicate. -TEST(ExitStatusPredicateTest, ExitedWithCode) { - // On Windows, the process's exit code is the same as its exit status, - // so the predicate just compares the its input with its parameter. - EXPECT_TRUE(testing::ExitedWithCode(0)(0)); - EXPECT_TRUE(testing::ExitedWithCode(1)(1)); - EXPECT_TRUE(testing::ExitedWithCode(42)(42)); - EXPECT_FALSE(testing::ExitedWithCode(0)(1)); - EXPECT_FALSE(testing::ExitedWithCode(1)(0)); -} - -# else - -// Returns the exit status of a process that calls _exit(2) with a -// given exit code. This is a helper function for the -// ExitStatusPredicateTest test suite. -static int NormalExitStatus(int exit_code) { - pid_t child_pid = fork(); - if (child_pid == 0) { - _exit(exit_code); - } - int status; - waitpid(child_pid, &status, 0); - return status; -} - -// Returns the exit status of a process that raises a given signal. -// If the signal does not cause the process to die, then it returns -// instead the exit status of a process that exits normally with exit -// code 1. This is a helper function for the ExitStatusPredicateTest -// test suite. -static int KilledExitStatus(int signum) { - pid_t child_pid = fork(); - if (child_pid == 0) { - raise(signum); - _exit(1); - } - int status; - waitpid(child_pid, &status, 0); - return status; -} - -// Tests the ExitedWithCode predicate. -TEST(ExitStatusPredicateTest, ExitedWithCode) { - const int status0 = NormalExitStatus(0); - const int status1 = NormalExitStatus(1); - const int status42 = NormalExitStatus(42); - const testing::ExitedWithCode pred0(0); - const testing::ExitedWithCode pred1(1); - const testing::ExitedWithCode pred42(42); - EXPECT_PRED1(pred0, status0); - EXPECT_PRED1(pred1, status1); - EXPECT_PRED1(pred42, status42); - EXPECT_FALSE(pred0(status1)); - EXPECT_FALSE(pred42(status0)); - EXPECT_FALSE(pred1(status42)); -} - -// Tests the KilledBySignal predicate. -TEST(ExitStatusPredicateTest, KilledBySignal) { - const int status_segv = KilledExitStatus(SIGSEGV); - const int status_kill = KilledExitStatus(SIGKILL); - const testing::KilledBySignal pred_segv(SIGSEGV); - const testing::KilledBySignal pred_kill(SIGKILL); - EXPECT_PRED1(pred_segv, status_segv); - EXPECT_PRED1(pred_kill, status_kill); - EXPECT_FALSE(pred_segv(status_kill)); - EXPECT_FALSE(pred_kill(status_segv)); -} - -# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA - -// Tests that the death test macros expand to code which may or may not -// be followed by operator<<, and that in either case the complete text -// comprises only a single C++ statement. -TEST_F(TestForDeathTest, SingleStatement) { - if (AlwaysFalse()) - // This would fail if executed; this is a compilation test only - ASSERT_DEATH(return, ""); - - if (AlwaysTrue()) - EXPECT_DEATH(_exit(1), ""); - else - // This empty "else" branch is meant to ensure that EXPECT_DEATH - // doesn't expand into an "if" statement without an "else" - ; - - if (AlwaysFalse()) - ASSERT_DEATH(return, "") << "did not die"; - - if (AlwaysFalse()) - ; - else - EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3; -} - -void DieWithEmbeddedNul() { - fprintf(stderr, "Hello%cmy null world.\n", '\0'); - fflush(stderr); - _exit(1); -} - -# if GTEST_USES_PCRE - -// Tests that EXPECT_DEATH and ASSERT_DEATH work when the error -// message has a NUL character in it. -TEST_F(TestForDeathTest, EmbeddedNulInMessage) { - EXPECT_DEATH(DieWithEmbeddedNul(), "my null world"); - ASSERT_DEATH(DieWithEmbeddedNul(), "my null world"); -} - -# endif // GTEST_USES_PCRE - -// Tests that death test macros expand to code which interacts well with switch -// statements. -TEST_F(TestForDeathTest, SwitchStatement) { - // Microsoft compiler usually complains about switch statements without - // case labels. We suppress that warning for this test. - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) - - switch (0) - default: - ASSERT_DEATH(_exit(1), "") << "exit in default switch handler"; - - switch (0) - case 0: - EXPECT_DEATH(_exit(1), "") << "exit in switch case"; - - GTEST_DISABLE_MSC_WARNINGS_POP_() -} - -// Tests that a static member function can be used in a "fast" style -// death test. -TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) { - testing::GTEST_FLAG(death_test_style) = "fast"; - ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember"); -} - -// Tests that a method of the test fixture can be used in a "fast" -// style death test. -TEST_F(TestForDeathTest, MemberFunctionFastStyle) { - testing::GTEST_FLAG(death_test_style) = "fast"; - should_die_ = true; - EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction"); -} - -void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); } - -// Tests that death tests work even if the current directory has been -// changed. -TEST_F(TestForDeathTest, FastDeathTestInChangedDir) { - testing::GTEST_FLAG(death_test_style) = "fast"; - - ChangeToRootDir(); - EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); - - ChangeToRootDir(); - ASSERT_DEATH(_exit(1), ""); -} - -# if GTEST_OS_LINUX -void SigprofAction(int, siginfo_t*, void*) { /* no op */ } - -// Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms). -void SetSigprofActionAndTimer() { - struct itimerval timer; - timer.it_interval.tv_sec = 0; - timer.it_interval.tv_usec = 1; - timer.it_value = timer.it_interval; - ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL)); - struct sigaction signal_action; - memset(&signal_action, 0, sizeof(signal_action)); - sigemptyset(&signal_action.sa_mask); - signal_action.sa_sigaction = SigprofAction; - signal_action.sa_flags = SA_RESTART | SA_SIGINFO; - ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, NULL)); -} - -// Disables ITIMER_PROF timer and ignores SIGPROF signal. -void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) { - struct itimerval timer; - timer.it_interval.tv_sec = 0; - timer.it_interval.tv_usec = 0; - timer.it_value = timer.it_interval; - ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL)); - struct sigaction signal_action; - memset(&signal_action, 0, sizeof(signal_action)); - sigemptyset(&signal_action.sa_mask); - signal_action.sa_handler = SIG_IGN; - ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action)); -} - -// Tests that death tests work when SIGPROF handler and timer are set. -TEST_F(TestForDeathTest, FastSigprofActionSet) { - testing::GTEST_FLAG(death_test_style) = "fast"; - SetSigprofActionAndTimer(); - EXPECT_DEATH(_exit(1), ""); - struct sigaction old_signal_action; - DisableSigprofActionAndTimer(&old_signal_action); - EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction); -} - -TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; - SetSigprofActionAndTimer(); - EXPECT_DEATH(_exit(1), ""); - struct sigaction old_signal_action; - DisableSigprofActionAndTimer(&old_signal_action); - EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction); -} -# endif // GTEST_OS_LINUX - -// Repeats a representative sample of death tests in the "threadsafe" style: - -TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; - ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember"); -} - -TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; - should_die_ = true; - EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction"); -} - -TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; - - for (int i = 0; i < 3; ++i) - EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i; -} - -TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; - - ChangeToRootDir(); - EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); - - ChangeToRootDir(); - ASSERT_DEATH(_exit(1), ""); -} - -TEST_F(TestForDeathTest, MixedStyles) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; - EXPECT_DEATH(_exit(1), ""); - testing::GTEST_FLAG(death_test_style) = "fast"; - EXPECT_DEATH(_exit(1), ""); -} - -# if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD - -namespace { - -bool pthread_flag; - -void SetPthreadFlag() { - pthread_flag = true; -} - -} // namespace - -TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { - if (!testing::GTEST_FLAG(death_test_use_fork)) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; - pthread_flag = false; - ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL)); - ASSERT_DEATH(_exit(1), ""); - ASSERT_FALSE(pthread_flag); - } -} - -# endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD - -// Tests that a method of another class can be used in a death test. -TEST_F(TestForDeathTest, MethodOfAnotherClass) { - const MayDie x(true); - ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction"); -} - -// Tests that a global function can be used in a death test. -TEST_F(TestForDeathTest, GlobalFunction) { - EXPECT_DEATH(GlobalFunction(), "GlobalFunction"); -} - -// Tests that any value convertible to an RE works as a second -// argument to EXPECT_DEATH. -TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { - static const char regex_c_str[] = "GlobalFunction"; - EXPECT_DEATH(GlobalFunction(), regex_c_str); - - const testing::internal::RE regex(regex_c_str); - EXPECT_DEATH(GlobalFunction(), regex); - -# if GTEST_HAS_GLOBAL_STRING - - const ::string regex_str(regex_c_str); - EXPECT_DEATH(GlobalFunction(), regex_str); - -# endif // GTEST_HAS_GLOBAL_STRING - -# if !GTEST_USES_PCRE - - const ::std::string regex_std_str(regex_c_str); - EXPECT_DEATH(GlobalFunction(), regex_std_str); - -# endif // !GTEST_USES_PCRE -} - -// Tests that a non-void function can be used in a death test. -TEST_F(TestForDeathTest, NonVoidFunction) { - ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction"); -} - -// Tests that functions that take parameter(s) can be used in a death test. -TEST_F(TestForDeathTest, FunctionWithParameter) { - EXPECT_DEATH(DieIf(true), "DieIf\\(\\)"); - EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan"); -} - -// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture. -TEST_F(TestForDeathTest, OutsideFixture) { - DeathTestSubroutine(); -} - -// Tests that death tests can be done inside a loop. -TEST_F(TestForDeathTest, InsideLoop) { - for (int i = 0; i < 5; i++) { - EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i; - } -} - -// Tests that a compound statement can be used in a death test. -TEST_F(TestForDeathTest, CompoundStatement) { - EXPECT_DEATH({ // NOLINT - const int x = 2; - const int y = x + 1; - DieIfLessThan(x, y); - }, - "DieIfLessThan"); -} - -// Tests that code that doesn't die causes a death test to fail. -TEST_F(TestForDeathTest, DoesNotDie) { - EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), - "failed to die"); -} - -// Tests that a death test fails when the error message isn't expected. -TEST_F(TestForDeathTest, ErrorMessageMismatch) { - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message."; - }, "died but not with expected error"); -} - -// On exit, *aborted will be true iff the EXPECT_DEATH() statement -// aborted the function. -void ExpectDeathTestHelper(bool* aborted) { - *aborted = true; - EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. - *aborted = false; -} - -// Tests that EXPECT_DEATH doesn't abort the test on failure. -TEST_F(TestForDeathTest, EXPECT_DEATH) { - bool aborted = true; - EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), - "failed to die"); - EXPECT_FALSE(aborted); -} - -// Tests that ASSERT_DEATH does abort the test on failure. -TEST_F(TestForDeathTest, ASSERT_DEATH) { - static bool aborted; - EXPECT_FATAL_FAILURE({ // NOLINT - aborted = true; - ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. - aborted = false; - }, "failed to die"); - EXPECT_TRUE(aborted); -} - -// Tests that EXPECT_DEATH evaluates the arguments exactly once. -TEST_F(TestForDeathTest, SingleEvaluation) { - int x = 3; - EXPECT_DEATH(DieIf((++x) == 4), "DieIf"); - - const char* regex = "DieIf"; - const char* regex_save = regex; - EXPECT_DEATH(DieIfLessThan(3, 4), regex++); - EXPECT_EQ(regex_save + 1, regex); -} - -// Tests that run-away death tests are reported as failures. -TEST_F(TestForDeathTest, RunawayIsFailure) { - EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast(0), "Foo"), - "failed to die."); -} - -// Tests that death tests report executing 'return' in the statement as -// failure. -TEST_F(TestForDeathTest, ReturnIsFailure) { - EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"), - "illegal return in test statement."); -} - -// Tests that EXPECT_DEBUG_DEATH works as expected, that is, you can stream a -// message to it, and in debug mode it: -// 1. Asserts on death. -// 2. Has no side effect. -// -// And in opt mode, it: -// 1. Has side effects but does not assert. -TEST_F(TestForDeathTest, TestExpectDebugDeath) { - int sideeffect = 0; - - // Put the regex in a local variable to make sure we don't get an "unused" - // warning in opt mode. - const char* regex = "death.*DieInDebugElse12"; - - EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex) - << "Must accept a streamed message"; - -# ifdef NDEBUG - - // Checks that the assignment occurs in opt mode (sideeffect). - EXPECT_EQ(12, sideeffect); - -# else - - // Checks that the assignment does not occur in dbg mode (no sideeffect). - EXPECT_EQ(0, sideeffect); - -# endif -} - -// Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a -// message to it, and in debug mode it: -// 1. Asserts on death. -// 2. Has no side effect. -// -// And in opt mode, it: -// 1. Has side effects but does not assert. -TEST_F(TestForDeathTest, TestAssertDebugDeath) { - int sideeffect = 0; - - ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12") - << "Must accept a streamed message"; - -# ifdef NDEBUG - - // Checks that the assignment occurs in opt mode (sideeffect). - EXPECT_EQ(12, sideeffect); - -# else - - // Checks that the assignment does not occur in dbg mode (no sideeffect). - EXPECT_EQ(0, sideeffect); - -# endif -} - -# ifndef NDEBUG - -void ExpectDebugDeathHelper(bool* aborted) { - *aborted = true; - EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail."; - *aborted = false; -} - -# if GTEST_OS_WINDOWS -TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { - 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; - abort(); - }, ""); -} -# endif // GTEST_OS_WINDOWS - -// Tests that EXPECT_DEBUG_DEATH in debug mode does not abort -// the function. -TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) { - bool aborted = true; - EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), ""); - EXPECT_FALSE(aborted); -} - -void AssertDebugDeathHelper(bool* aborted) { - *aborted = true; - GTEST_LOG_(INFO) << "Before ASSERT_DEBUG_DEATH"; - ASSERT_DEBUG_DEATH(GTEST_LOG_(INFO) << "In ASSERT_DEBUG_DEATH"; return, "") - << "This is expected to fail."; - GTEST_LOG_(INFO) << "After ASSERT_DEBUG_DEATH"; - *aborted = false; -} - -// Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on -// failure. -TEST_F(TestForDeathTest, AssertDebugDeathAborts) { - static bool aborted; - aborted = false; - EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); - EXPECT_TRUE(aborted); -} - -TEST_F(TestForDeathTest, AssertDebugDeathAborts2) { - static bool aborted; - aborted = false; - EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); - EXPECT_TRUE(aborted); -} - -TEST_F(TestForDeathTest, AssertDebugDeathAborts3) { - static bool aborted; - aborted = false; - EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); - EXPECT_TRUE(aborted); -} - -TEST_F(TestForDeathTest, AssertDebugDeathAborts4) { - static bool aborted; - aborted = false; - EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); - EXPECT_TRUE(aborted); -} - -TEST_F(TestForDeathTest, AssertDebugDeathAborts5) { - static bool aborted; - aborted = false; - EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); - EXPECT_TRUE(aborted); -} - -TEST_F(TestForDeathTest, AssertDebugDeathAborts6) { - static bool aborted; - aborted = false; - EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); - EXPECT_TRUE(aborted); -} - -TEST_F(TestForDeathTest, AssertDebugDeathAborts7) { - static bool aborted; - aborted = false; - EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); - EXPECT_TRUE(aborted); -} - -TEST_F(TestForDeathTest, AssertDebugDeathAborts8) { - static bool aborted; - aborted = false; - EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); - EXPECT_TRUE(aborted); -} - -TEST_F(TestForDeathTest, AssertDebugDeathAborts9) { - static bool aborted; - aborted = false; - EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); - EXPECT_TRUE(aborted); -} - -TEST_F(TestForDeathTest, AssertDebugDeathAborts10) { - static bool aborted; - aborted = false; - EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); - EXPECT_TRUE(aborted); -} - -# endif // _NDEBUG - -// Tests the *_EXIT family of macros, using a variety of predicates. -static void TestExitMacros() { - EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); - ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), ""); - -# if GTEST_OS_WINDOWS - - // Of all signals effects on the process exit code, only those of SIGABRT - // are documented on Windows. - // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx. - EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar"; - -# elif !GTEST_OS_FUCHSIA - - // Fuchsia has no unix signals. - EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo"; - ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar"; - - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "") - << "This failure is expected, too."; - }, "This failure is expected, too."); - -# endif // GTEST_OS_WINDOWS - - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "") - << "This failure is expected."; - }, "This failure is expected."); -} - -TEST_F(TestForDeathTest, ExitMacros) { - TestExitMacros(); -} - -TEST_F(TestForDeathTest, ExitMacrosUsingFork) { - testing::GTEST_FLAG(death_test_use_fork) = true; - TestExitMacros(); -} - -TEST_F(TestForDeathTest, InvalidStyle) { - testing::GTEST_FLAG(death_test_style) = "rococo"; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_DEATH(_exit(0), "") << "This failure is expected."; - }, "This failure is expected."); -} - -TEST_F(TestForDeathTest, DeathTestFailedOutput) { - testing::GTEST_FLAG(death_test_style) = "fast"; - EXPECT_NONFATAL_FAILURE( - EXPECT_DEATH(DieWithMessage("death\n"), - "expected message"), - "Actual msg:\n" - "[ DEATH ] death\n"); -} - -TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) { - testing::GTEST_FLAG(death_test_style) = "fast"; - EXPECT_NONFATAL_FAILURE( - EXPECT_DEATH({ - fprintf(stderr, "returning\n"); - fflush(stderr); - return; - }, ""), - " Result: illegal return in test statement.\n" - " Error msg:\n" - "[ DEATH ] returning\n"); -} - -TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) { - testing::GTEST_FLAG(death_test_style) = "fast"; - EXPECT_NONFATAL_FAILURE( - EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"), - testing::ExitedWithCode(3), - "expected message"), - " Result: died but not with expected exit code:\n" - " Exited with exit status 1\n" - "Actual msg:\n" - "[ DEATH ] exiting with rc 1\n"); -} - -TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) { - testing::GTEST_FLAG(death_test_style) = "fast"; - EXPECT_NONFATAL_FAILURE( - EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"), - "line 1\nxyz\nline 3\n"), - "Actual msg:\n" - "[ DEATH ] line 1\n" - "[ DEATH ] line 2\n" - "[ DEATH ] line 3\n"); -} - -TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) { - testing::GTEST_FLAG(death_test_style) = "fast"; - EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"), - "line 1\nline 2\nline 3\n"); -} - -// A DeathTestFactory that returns MockDeathTests. -class MockDeathTestFactory : public DeathTestFactory { - public: - MockDeathTestFactory(); - virtual bool Create(const char* statement, - const ::testing::internal::RE* regex, - const char* file, int line, DeathTest** test); - - // Sets the parameters for subsequent calls to Create. - void SetParameters(bool create, DeathTest::TestRole role, - int status, bool passed); - - // Accessors. - int AssumeRoleCalls() const { return assume_role_calls_; } - int WaitCalls() const { return wait_calls_; } - size_t PassedCalls() const { return passed_args_.size(); } - bool PassedArgument(int n) const { return passed_args_[n]; } - size_t AbortCalls() const { return abort_args_.size(); } - DeathTest::AbortReason AbortArgument(int n) const { - return abort_args_[n]; - } - bool TestDeleted() const { return test_deleted_; } - - private: - friend class MockDeathTest; - // If true, Create will return a MockDeathTest; otherwise it returns - // NULL. - bool create_; - // The value a MockDeathTest will return from its AssumeRole method. - DeathTest::TestRole role_; - // The value a MockDeathTest will return from its Wait method. - int status_; - // The value a MockDeathTest will return from its Passed method. - bool passed_; - - // Number of times AssumeRole was called. - int assume_role_calls_; - // Number of times Wait was called. - int wait_calls_; - // The arguments to the calls to Passed since the last call to - // SetParameters. - std::vector passed_args_; - // The arguments to the calls to Abort since the last call to - // SetParameters. - std::vector abort_args_; - // True if the last MockDeathTest returned by Create has been - // deleted. - bool test_deleted_; -}; - - -// A DeathTest implementation useful in testing. It returns values set -// at its creation from its various inherited DeathTest methods, and -// reports calls to those methods to its parent MockDeathTestFactory -// object. -class MockDeathTest : public DeathTest { - public: - MockDeathTest(MockDeathTestFactory *parent, - TestRole role, int status, bool passed) : - parent_(parent), role_(role), status_(status), passed_(passed) { - } - virtual ~MockDeathTest() { - parent_->test_deleted_ = true; - } - virtual TestRole AssumeRole() { - ++parent_->assume_role_calls_; - return role_; - } - virtual int Wait() { - ++parent_->wait_calls_; - return status_; - } - virtual bool Passed(bool exit_status_ok) { - parent_->passed_args_.push_back(exit_status_ok); - return passed_; - } - virtual void Abort(AbortReason reason) { - parent_->abort_args_.push_back(reason); - } - - private: - MockDeathTestFactory* const parent_; - const TestRole role_; - const int status_; - const bool passed_; -}; - - -// MockDeathTestFactory constructor. -MockDeathTestFactory::MockDeathTestFactory() - : create_(true), - role_(DeathTest::OVERSEE_TEST), - status_(0), - passed_(true), - assume_role_calls_(0), - wait_calls_(0), - passed_args_(), - abort_args_() { -} - - -// Sets the parameters for subsequent calls to Create. -void MockDeathTestFactory::SetParameters(bool create, - DeathTest::TestRole role, - int status, bool passed) { - create_ = create; - role_ = role; - status_ = status; - passed_ = passed; - - assume_role_calls_ = 0; - wait_calls_ = 0; - passed_args_.clear(); - abort_args_.clear(); -} - - -// Sets test to NULL (if create_ is false) or to the address of a new -// MockDeathTest object with parameters taken from the last call -// to SetParameters (if create_ is true). Always returns true. -bool MockDeathTestFactory::Create(const char* /*statement*/, - const ::testing::internal::RE* /*regex*/, - const char* /*file*/, - int /*line*/, - DeathTest** test) { - test_deleted_ = false; - if (create_) { - *test = new MockDeathTest(this, role_, status_, passed_); - } else { - *test = NULL; - } - return true; -} - -// A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro. -// It installs a MockDeathTestFactory that is used for the duration -// of the test case. -class MacroLogicDeathTest : public testing::Test { - protected: - static testing::internal::ReplaceDeathTestFactory* replacer_; - static MockDeathTestFactory* factory_; - - static void SetUpTestCase() { - factory_ = new MockDeathTestFactory; - replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_); - } - - static void TearDownTestCase() { - delete replacer_; - replacer_ = NULL; - delete factory_; - factory_ = NULL; - } - - // Runs a death test that breaks the rules by returning. Such a death - // test cannot be run directly from a test routine that uses a - // MockDeathTest, or the remainder of the routine will not be executed. - static void RunReturningDeathTest(bool* flag) { - ASSERT_DEATH({ // NOLINT - *flag = true; - return; - }, ""); - } -}; - -testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_ - = NULL; -MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL; - - -// Test that nothing happens when the factory doesn't return a DeathTest: -TEST_F(MacroLogicDeathTest, NothingHappens) { - bool flag = false; - factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true); - EXPECT_DEATH(flag = true, ""); - EXPECT_FALSE(flag); - EXPECT_EQ(0, factory_->AssumeRoleCalls()); - EXPECT_EQ(0, factory_->WaitCalls()); - EXPECT_EQ(0U, factory_->PassedCalls()); - EXPECT_EQ(0U, factory_->AbortCalls()); - EXPECT_FALSE(factory_->TestDeleted()); -} - -// Test that the parent process doesn't run the death test code, -// and that the Passed method returns false when the (simulated) -// child process exits with status 0: -TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) { - bool flag = false; - factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true); - EXPECT_DEATH(flag = true, ""); - EXPECT_FALSE(flag); - EXPECT_EQ(1, factory_->AssumeRoleCalls()); - EXPECT_EQ(1, factory_->WaitCalls()); - ASSERT_EQ(1U, factory_->PassedCalls()); - EXPECT_FALSE(factory_->PassedArgument(0)); - EXPECT_EQ(0U, factory_->AbortCalls()); - EXPECT_TRUE(factory_->TestDeleted()); -} - -// Tests that the Passed method was given the argument "true" when -// the (simulated) child process exits with status 1: -TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) { - bool flag = false; - factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true); - EXPECT_DEATH(flag = true, ""); - EXPECT_FALSE(flag); - EXPECT_EQ(1, factory_->AssumeRoleCalls()); - EXPECT_EQ(1, factory_->WaitCalls()); - ASSERT_EQ(1U, factory_->PassedCalls()); - EXPECT_TRUE(factory_->PassedArgument(0)); - EXPECT_EQ(0U, factory_->AbortCalls()); - EXPECT_TRUE(factory_->TestDeleted()); -} - -// Tests that the (simulated) child process executes the death test -// code, and is aborted with the correct AbortReason if it -// executes a return statement. -TEST_F(MacroLogicDeathTest, ChildPerformsReturn) { - bool flag = false; - factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true); - RunReturningDeathTest(&flag); - EXPECT_TRUE(flag); - EXPECT_EQ(1, factory_->AssumeRoleCalls()); - EXPECT_EQ(0, factory_->WaitCalls()); - EXPECT_EQ(0U, factory_->PassedCalls()); - EXPECT_EQ(1U, factory_->AbortCalls()); - EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT, - factory_->AbortArgument(0)); - EXPECT_TRUE(factory_->TestDeleted()); -} - -// Tests that the (simulated) child process is aborted with the -// correct AbortReason if it does not die. -TEST_F(MacroLogicDeathTest, ChildDoesNotDie) { - bool flag = false; - factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true); - EXPECT_DEATH(flag = true, ""); - EXPECT_TRUE(flag); - EXPECT_EQ(1, factory_->AssumeRoleCalls()); - EXPECT_EQ(0, factory_->WaitCalls()); - EXPECT_EQ(0U, factory_->PassedCalls()); - // This time there are two calls to Abort: one since the test didn't - // die, and another from the ReturnSentinel when it's destroyed. The - // sentinel normally isn't destroyed if a test doesn't die, since - // _exit(2) is called in that case by ForkingDeathTest, but not by - // our MockDeathTest. - ASSERT_EQ(2U, factory_->AbortCalls()); - EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, - factory_->AbortArgument(0)); - EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT, - factory_->AbortArgument(1)); - EXPECT_TRUE(factory_->TestDeleted()); -} - -// Tests that a successful death test does not register a successful -// test part. -TEST(SuccessRegistrationDeathTest, NoSuccessPart) { - EXPECT_DEATH(_exit(1), ""); - EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); -} - -TEST(StreamingAssertionsDeathTest, DeathTest) { - EXPECT_DEATH(_exit(1), "") << "unexpected failure"; - ASSERT_DEATH(_exit(1), "") << "unexpected failure"; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_DEATH(_exit(0), "") << "expected failure"; - }, "expected failure"); - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_DEATH(_exit(0), "") << "expected failure"; - }, "expected failure"); -} - -// Tests that GetLastErrnoDescription returns an empty string when the -// last error is 0 and non-empty string when it is non-zero. -TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) { - errno = ENOENT; - EXPECT_STRNE("", GetLastErrnoDescription().c_str()); - errno = 0; - EXPECT_STREQ("", GetLastErrnoDescription().c_str()); -} - -# if GTEST_OS_WINDOWS -TEST(AutoHandleTest, AutoHandleWorks) { - HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); - ASSERT_NE(INVALID_HANDLE_VALUE, handle); - - // Tests that the AutoHandle is correctly initialized with a handle. - testing::internal::AutoHandle auto_handle(handle); - EXPECT_EQ(handle, auto_handle.Get()); - - // Tests that Reset assigns INVALID_HANDLE_VALUE. - // Note that this cannot verify whether the original handle is closed. - auto_handle.Reset(); - EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get()); - - // Tests that Reset assigns the new handle. - // Note that this cannot verify whether the original handle is closed. - handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); - ASSERT_NE(INVALID_HANDLE_VALUE, handle); - auto_handle.Reset(handle); - EXPECT_EQ(handle, auto_handle.Get()); - - // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default. - testing::internal::AutoHandle auto_handle2; - EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get()); -} -# endif // GTEST_OS_WINDOWS - -# if GTEST_OS_WINDOWS -typedef unsigned __int64 BiggestParsable; -typedef signed __int64 BiggestSignedParsable; -# else -typedef unsigned long long BiggestParsable; -typedef signed long long BiggestSignedParsable; -# endif // GTEST_OS_WINDOWS - -// We cannot use std::numeric_limits::max() as it clashes with the -// max() macro defined by . -const BiggestParsable kBiggestParsableMax = ULLONG_MAX; -const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX; - -TEST(ParseNaturalNumberTest, RejectsInvalidFormat) { - BiggestParsable result = 0; - - // Rejects non-numbers. - EXPECT_FALSE(ParseNaturalNumber("non-number string", &result)); - - // Rejects numbers with whitespace prefix. - EXPECT_FALSE(ParseNaturalNumber(" 123", &result)); - - // Rejects negative numbers. - EXPECT_FALSE(ParseNaturalNumber("-123", &result)); - - // Rejects numbers starting with a plus sign. - EXPECT_FALSE(ParseNaturalNumber("+123", &result)); - errno = 0; -} - -TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) { - BiggestParsable result = 0; - - EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result)); - - signed char char_result = 0; - EXPECT_FALSE(ParseNaturalNumber("200", &char_result)); - errno = 0; -} - -TEST(ParseNaturalNumberTest, AcceptsValidNumbers) { - BiggestParsable result = 0; - - result = 0; - ASSERT_TRUE(ParseNaturalNumber("123", &result)); - EXPECT_EQ(123U, result); - - // Check 0 as an edge case. - result = 1; - ASSERT_TRUE(ParseNaturalNumber("0", &result)); - EXPECT_EQ(0U, result); - - result = 1; - ASSERT_TRUE(ParseNaturalNumber("00000", &result)); - EXPECT_EQ(0U, result); -} - -TEST(ParseNaturalNumberTest, AcceptsTypeLimits) { - Message msg; - msg << kBiggestParsableMax; - - BiggestParsable result = 0; - EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result)); - EXPECT_EQ(kBiggestParsableMax, result); - - Message msg2; - msg2 << kBiggestSignedParsableMax; - - BiggestSignedParsable signed_result = 0; - EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result)); - EXPECT_EQ(kBiggestSignedParsableMax, signed_result); - - Message msg3; - msg3 << INT_MAX; - - int int_result = 0; - EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result)); - EXPECT_EQ(INT_MAX, int_result); - - Message msg4; - msg4 << UINT_MAX; - - unsigned int uint_result = 0; - EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result)); - EXPECT_EQ(UINT_MAX, uint_result); -} - -TEST(ParseNaturalNumberTest, WorksForShorterIntegers) { - short short_result = 0; - ASSERT_TRUE(ParseNaturalNumber("123", &short_result)); - EXPECT_EQ(123, short_result); - - signed char char_result = 0; - ASSERT_TRUE(ParseNaturalNumber("123", &char_result)); - EXPECT_EQ(123, char_result); -} - -# if GTEST_OS_WINDOWS -TEST(EnvironmentTest, HandleFitsIntoSizeT) { - // TODO(vladl@google.com): Remove this test after this condition is verified - // in a static assertion in gtest-death-test.cc in the function - // GetStatusFileDescriptor. - ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t)); -} -# endif // GTEST_OS_WINDOWS - -// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger -// failures when death tests are available on the system. -TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) { - EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"), - "death inside CondDeathTestExpectMacro"); - ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"), - "death inside CondDeathTestAssertMacro"); - - // Empty statement will not crash, which must trigger a failure. - EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), ""); - EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), ""); -} - -TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) { - testing::GTEST_FLAG(death_test_style) = "fast"; - EXPECT_FALSE(InDeathTestChild()); - EXPECT_DEATH({ - fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); - fflush(stderr); - _exit(1); - }, "Inside"); -} - -TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; - EXPECT_FALSE(InDeathTestChild()); - EXPECT_DEATH({ - fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); - fflush(stderr); - _exit(1); - }, "Inside"); -} - -#else // !GTEST_HAS_DEATH_TEST follows - -using testing::internal::CaptureStderr; -using testing::internal::GetCapturedStderr; - -// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still -// defined but do not trigger failures when death tests are not available on -// the system. -TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) { - // Empty statement will not crash, but that should not trigger a failure - // when death tests are not supported. - CaptureStderr(); - EXPECT_DEATH_IF_SUPPORTED(;, ""); - std::string output = GetCapturedStderr(); - ASSERT_TRUE(NULL != strstr(output.c_str(), - "Death tests are not supported on this platform")); - ASSERT_TRUE(NULL != strstr(output.c_str(), ";")); - - // The streamed message should not be printed as there is no test failure. - CaptureStderr(); - EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; - output = GetCapturedStderr(); - ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message")); - - CaptureStderr(); - ASSERT_DEATH_IF_SUPPORTED(;, ""); // NOLINT - output = GetCapturedStderr(); - ASSERT_TRUE(NULL != strstr(output.c_str(), - "Death tests are not supported on this platform")); - ASSERT_TRUE(NULL != strstr(output.c_str(), ";")); - - CaptureStderr(); - ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; // NOLINT - output = GetCapturedStderr(); - ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message")); -} - -void FuncWithAssert(int* n) { - ASSERT_DEATH_IF_SUPPORTED(return;, ""); - (*n)++; -} - -// Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current -// function (as ASSERT_DEATH does) if death tests are not supported. -TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) { - int n = 0; - FuncWithAssert(&n); - EXPECT_EQ(1, n); -} - -#endif // !GTEST_HAS_DEATH_TEST - -// Tests that the death test macros expand to code which may or may not -// be followed by operator<<, and that in either case the complete text -// comprises only a single C++ statement. -// -// The syntax should work whether death tests are available or not. -TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) { - if (AlwaysFalse()) - // This would fail if executed; this is a compilation test only - ASSERT_DEATH_IF_SUPPORTED(return, ""); - - if (AlwaysTrue()) - EXPECT_DEATH_IF_SUPPORTED(_exit(1), ""); - else - // This empty "else" branch is meant to ensure that EXPECT_DEATH - // doesn't expand into an "if" statement without an "else" - ; // NOLINT - - if (AlwaysFalse()) - ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die"; - - if (AlwaysFalse()) - ; // NOLINT - else - EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3; -} - -// Tests that conditional death test macros expand to code which interacts -// well with switch statements. -TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) { - // Microsoft compiler usually complains about switch statements without - // case labels. We suppress that warning for this test. - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) - - switch (0) - default: - ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") - << "exit in default switch handler"; - - switch (0) - case 0: - EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case"; - - GTEST_DISABLE_MSC_WARNINGS_POP_() -} - -// Tests that a test case whose name ends with "DeathTest" works fine -// on Windows. -TEST(NotADeathTest, Test) { - SUCCEED(); -} diff --git a/googletest/test/gtest_uninitialized_test.py b/googletest/test/gtest_uninitialized_test.py deleted file mode 100755 index ae91f2a..0000000 --- a/googletest/test/gtest_uninitialized_test.py +++ /dev/null @@ -1,69 +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. - -"""Verifies that Google Test warns the user when not initialized properly.""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import gtest_test_utils - -COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_uninitialized_test_') - - -def Assert(condition): - if not condition: - raise AssertionError - - -def AssertEq(expected, actual): - if expected != actual: - print 'Expected: %s' % (expected,) - print ' Actual: %s' % (actual,) - raise AssertionError - - -def TestExitCodeAndOutput(command): - """Runs the given command and verifies its exit code and output.""" - - # Verifies that 'command' exits with code 1. - p = gtest_test_utils.Subprocess(command) - if p.exited and p.exit_code == 0: - Assert('IMPORTANT NOTICE' in p.output); - Assert('InitGoogleTest' in p.output) - - -class GTestUninitializedTest(gtest_test_utils.TestCase): - def testExitCodeAndOutput(self): - TestExitCodeAndOutput(COMMAND) - - -if __name__ == '__main__': - gtest_test_utils.Main() -- cgit v0.12 From 09fc73dde963132ded6595cdb724171c78436e52 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 15:34:30 -0400 Subject: more test changes --- googletest/test/BUILD.bazel | 14 + googletest/test/googletest-filepath-test.cc | 652 +++++++++++++++++++++++ googletest/test/googletest-json-outfiles-test.py | 162 ++++++ googletest/test/googletest-linked-ptr-test.cc | 154 ++++++ googletest/test/gtest-filepath_test.cc | 652 ----------------------- googletest/test/gtest-linked_ptr_test.cc | 154 ------ googletest/test/gtest-listener_test.cc | 311 ----------- 7 files changed, 982 insertions(+), 1117 deletions(-) create mode 100644 googletest/test/googletest-filepath-test.cc create mode 100644 googletest/test/googletest-json-outfiles-test.py create mode 100644 googletest/test/googletest-linked-ptr-test.cc delete mode 100644 googletest/test/gtest-filepath_test.cc delete mode 100644 googletest/test/gtest-linked_ptr_test.cc delete mode 100644 googletest/test/gtest-listener_test.cc diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 780b278..fdec685 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -448,3 +448,17 @@ py_test( data = [":gtest_testbridge_test_"], deps = [":gtest_test_utils"], ) + +py_test( + name = "googletest-json-outfiles-test", + size = "small", + srcs = [ + "googletest-json-outfiles-test.py", + "gtest_json_test_utils.py", + ], + data = [ + ":gtest_xml_outfile1_test_", + ":gtest_xml_outfile2_test_", + ], + deps = [":gtest_test_utils"], +) diff --git a/googletest/test/googletest-filepath-test.cc b/googletest/test/googletest-filepath-test.cc new file mode 100644 index 0000000..29cea3d --- /dev/null +++ b/googletest/test/googletest-filepath-test.cc @@ -0,0 +1,652 @@ +// 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. +// +// +// Google Test filepath utilities +// +// This file tests classes and functions used internally by +// Google Test. They are subject to change without notice. +// +// This file is #included from gtest-internal.h. +// Do not #include this file anywhere else! + +#include "gtest/internal/gtest-filepath.h" +#include "gtest/gtest.h" +#include "src/gtest-internal-inl.h" + +#if GTEST_OS_WINDOWS_MOBILE +# include // NOLINT +#elif GTEST_OS_WINDOWS +# include // NOLINT +#endif // GTEST_OS_WINDOWS_MOBILE + +namespace testing { +namespace internal { +namespace { + +#if GTEST_OS_WINDOWS_MOBILE +// TODO(wan@google.com): Move these to the POSIX adapter section in +// gtest-port.h. + +// Windows CE doesn't have the remove C function. +int remove(const char* path) { + LPCWSTR wpath = String::AnsiToUtf16(path); + int ret = DeleteFile(wpath) ? 0 : -1; + delete [] wpath; + return ret; +} +// Windows CE doesn't have the _rmdir C function. +int _rmdir(const char* path) { + FilePath filepath(path); + LPCWSTR wpath = String::AnsiToUtf16( + filepath.RemoveTrailingPathSeparator().c_str()); + int ret = RemoveDirectory(wpath) ? 0 : -1; + delete [] wpath; + return ret; +} + +#else + +TEST(GetCurrentDirTest, ReturnsCurrentDir) { + const FilePath original_dir = FilePath::GetCurrentDir(); + EXPECT_FALSE(original_dir.IsEmpty()); + + posix::ChDir(GTEST_PATH_SEP_); + const FilePath cwd = FilePath::GetCurrentDir(); + posix::ChDir(original_dir.c_str()); + +# if GTEST_OS_WINDOWS + + // Skips the ":". + const char* const cwd_without_drive = strchr(cwd.c_str(), ':'); + ASSERT_TRUE(cwd_without_drive != NULL); + EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1); + +# else + + EXPECT_EQ(GTEST_PATH_SEP_, cwd.string()); + +# endif +} + +#endif // GTEST_OS_WINDOWS_MOBILE + +TEST(IsEmptyTest, ReturnsTrueForEmptyPath) { + EXPECT_TRUE(FilePath("").IsEmpty()); +} + +TEST(IsEmptyTest, ReturnsFalseForNonEmptyPath) { + EXPECT_FALSE(FilePath("a").IsEmpty()); + EXPECT_FALSE(FilePath(".").IsEmpty()); + EXPECT_FALSE(FilePath("a/b").IsEmpty()); + EXPECT_FALSE(FilePath("a\\b\\").IsEmpty()); +} + +// RemoveDirectoryName "" -> "" +TEST(RemoveDirectoryNameTest, WhenEmptyName) { + EXPECT_EQ("", FilePath("").RemoveDirectoryName().string()); +} + +// RemoveDirectoryName "afile" -> "afile" +TEST(RemoveDirectoryNameTest, ButNoDirectory) { + EXPECT_EQ("afile", + FilePath("afile").RemoveDirectoryName().string()); +} + +// RemoveDirectoryName "/afile" -> "afile" +TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) { + EXPECT_EQ("afile", + FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); +} + +// RemoveDirectoryName "adir/" -> "" +TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) { + EXPECT_EQ("", + FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string()); +} + +// RemoveDirectoryName "adir/afile" -> "afile" +TEST(RemoveDirectoryNameTest, ShouldGiveFileName) { + EXPECT_EQ("afile", + FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); +} + +// RemoveDirectoryName "adir/subdir/afile" -> "afile" +TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) { + EXPECT_EQ("afile", + FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") + .RemoveDirectoryName().string()); +} + +#if GTEST_HAS_ALT_PATH_SEP_ + +// Tests that RemoveDirectoryName() works with the alternate separator +// on Windows. + +// RemoveDirectoryName("/afile") -> "afile" +TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileNameForAlternateSeparator) { + EXPECT_EQ("afile", FilePath("/afile").RemoveDirectoryName().string()); +} + +// RemoveDirectoryName("adir/") -> "" +TEST(RemoveDirectoryNameTest, WhereThereIsNoFileNameForAlternateSeparator) { + EXPECT_EQ("", FilePath("adir/").RemoveDirectoryName().string()); +} + +// RemoveDirectoryName("adir/afile") -> "afile" +TEST(RemoveDirectoryNameTest, ShouldGiveFileNameForAlternateSeparator) { + EXPECT_EQ("afile", FilePath("adir/afile").RemoveDirectoryName().string()); +} + +// RemoveDirectoryName("adir/subdir/afile") -> "afile" +TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileNameForAlternateSeparator) { + EXPECT_EQ("afile", + FilePath("adir/subdir/afile").RemoveDirectoryName().string()); +} + +#endif + +// RemoveFileName "" -> "./" +TEST(RemoveFileNameTest, EmptyName) { +#if GTEST_OS_WINDOWS_MOBILE + // On Windows CE, we use the root as the current directory. + EXPECT_EQ(GTEST_PATH_SEP_, FilePath("").RemoveFileName().string()); +#else + EXPECT_EQ("." GTEST_PATH_SEP_, FilePath("").RemoveFileName().string()); +#endif +} + +// RemoveFileName "adir/" -> "adir/" +TEST(RemoveFileNameTest, ButNoFile) { + EXPECT_EQ("adir" GTEST_PATH_SEP_, + FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string()); +} + +// RemoveFileName "adir/afile" -> "adir/" +TEST(RemoveFileNameTest, GivesDirName) { + EXPECT_EQ("adir" GTEST_PATH_SEP_, + FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveFileName().string()); +} + +// RemoveFileName "adir/subdir/afile" -> "adir/subdir/" +TEST(RemoveFileNameTest, GivesDirAndSubDirName) { + EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_, + FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") + .RemoveFileName().string()); +} + +// RemoveFileName "/afile" -> "/" +TEST(RemoveFileNameTest, GivesRootDir) { + EXPECT_EQ(GTEST_PATH_SEP_, + FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string()); +} + +#if GTEST_HAS_ALT_PATH_SEP_ + +// Tests that RemoveFileName() works with the alternate separator on +// Windows. + +// RemoveFileName("adir/") -> "adir/" +TEST(RemoveFileNameTest, ButNoFileForAlternateSeparator) { + EXPECT_EQ("adir" GTEST_PATH_SEP_, + FilePath("adir/").RemoveFileName().string()); +} + +// RemoveFileName("adir/afile") -> "adir/" +TEST(RemoveFileNameTest, GivesDirNameForAlternateSeparator) { + EXPECT_EQ("adir" GTEST_PATH_SEP_, + FilePath("adir/afile").RemoveFileName().string()); +} + +// RemoveFileName("adir/subdir/afile") -> "adir/subdir/" +TEST(RemoveFileNameTest, GivesDirAndSubDirNameForAlternateSeparator) { + EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_, + FilePath("adir/subdir/afile").RemoveFileName().string()); +} + +// RemoveFileName("/afile") -> "\" +TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) { + EXPECT_EQ(GTEST_PATH_SEP_, FilePath("/afile").RemoveFileName().string()); +} + +#endif + +TEST(MakeFileNameTest, GenerateWhenNumberIsZero) { + FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), + 0, "xml"); + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); +} + +TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) { + FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), + 12, "xml"); + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string()); +} + +TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) { + FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), + FilePath("bar"), 0, "xml"); + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); +} + +TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) { + FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), + FilePath("bar"), 12, "xml"); + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string()); +} + +TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) { + FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), + 0, "xml"); + EXPECT_EQ("bar.xml", actual.string()); +} + +TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) { + FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), + 14, "xml"); + EXPECT_EQ("bar_14.xml", actual.string()); +} + +TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) { + FilePath actual = FilePath::ConcatPaths(FilePath("foo"), + FilePath("bar.xml")); + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); +} + +TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) { + FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_), + FilePath("bar.xml")); + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); +} + +TEST(ConcatPathsTest, Path1BeingEmpty) { + FilePath actual = FilePath::ConcatPaths(FilePath(""), + FilePath("bar.xml")); + EXPECT_EQ("bar.xml", actual.string()); +} + +TEST(ConcatPathsTest, Path2BeingEmpty) { + FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath("")); + EXPECT_EQ("foo" GTEST_PATH_SEP_, actual.string()); +} + +TEST(ConcatPathsTest, BothPathBeingEmpty) { + FilePath actual = FilePath::ConcatPaths(FilePath(""), + FilePath("")); + EXPECT_EQ("", actual.string()); +} + +TEST(ConcatPathsTest, Path1ContainsPathSep) { + FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_ "bar"), + FilePath("foobar.xml")); + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "foobar.xml", + actual.string()); +} + +TEST(ConcatPathsTest, Path2ContainsPathSep) { + FilePath actual = FilePath::ConcatPaths( + FilePath("foo" GTEST_PATH_SEP_), + FilePath("bar" GTEST_PATH_SEP_ "bar.xml")); + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml", + actual.string()); +} + +TEST(ConcatPathsTest, Path2EndsWithPathSep) { + FilePath actual = FilePath::ConcatPaths(FilePath("foo"), + FilePath("bar" GTEST_PATH_SEP_)); + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string()); +} + +// RemoveTrailingPathSeparator "" -> "" +TEST(RemoveTrailingPathSeparatorTest, EmptyString) { + EXPECT_EQ("", FilePath("").RemoveTrailingPathSeparator().string()); +} + +// RemoveTrailingPathSeparator "foo" -> "foo" +TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) { + EXPECT_EQ("foo", FilePath("foo").RemoveTrailingPathSeparator().string()); +} + +// RemoveTrailingPathSeparator "foo/" -> "foo" +TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) { + EXPECT_EQ("foo", + FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string()); +#if GTEST_HAS_ALT_PATH_SEP_ + EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string()); +#endif +} + +// RemoveTrailingPathSeparator "foo/bar/" -> "foo/bar/" +TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) { + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", + FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_) + .RemoveTrailingPathSeparator().string()); +} + +// RemoveTrailingPathSeparator "foo/bar" -> "foo/bar" +TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) { + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", + FilePath("foo" GTEST_PATH_SEP_ "bar") + .RemoveTrailingPathSeparator().string()); +} + +TEST(DirectoryTest, RootDirectoryExists) { +#if GTEST_OS_WINDOWS // We are on Windows. + char current_drive[_MAX_PATH]; // NOLINT + current_drive[0] = static_cast(_getdrive() + 'A' - 1); + current_drive[1] = ':'; + current_drive[2] = '\\'; + current_drive[3] = '\0'; + EXPECT_TRUE(FilePath(current_drive).DirectoryExists()); +#else + EXPECT_TRUE(FilePath("/").DirectoryExists()); +#endif // GTEST_OS_WINDOWS +} + +#if GTEST_OS_WINDOWS +TEST(DirectoryTest, RootOfWrongDriveDoesNotExists) { + const int saved_drive_ = _getdrive(); + // Find a drive that doesn't exist. Start with 'Z' to avoid common ones. + for (char drive = 'Z'; drive >= 'A'; drive--) + if (_chdrive(drive - 'A' + 1) == -1) { + char non_drive[_MAX_PATH]; // NOLINT + non_drive[0] = drive; + non_drive[1] = ':'; + non_drive[2] = '\\'; + non_drive[3] = '\0'; + EXPECT_FALSE(FilePath(non_drive).DirectoryExists()); + break; + } + _chdrive(saved_drive_); +} +#endif // GTEST_OS_WINDOWS + +#if !GTEST_OS_WINDOWS_MOBILE +// Windows CE _does_ consider an empty directory to exist. +TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) { + EXPECT_FALSE(FilePath("").DirectoryExists()); +} +#endif // !GTEST_OS_WINDOWS_MOBILE + +TEST(DirectoryTest, CurrentDirectoryExists) { +#if GTEST_OS_WINDOWS // We are on Windows. +# ifndef _WIN32_CE // Windows CE doesn't have a current directory. + + EXPECT_TRUE(FilePath(".").DirectoryExists()); + EXPECT_TRUE(FilePath(".\\").DirectoryExists()); + +# endif // _WIN32_CE +#else + EXPECT_TRUE(FilePath(".").DirectoryExists()); + EXPECT_TRUE(FilePath("./").DirectoryExists()); +#endif // GTEST_OS_WINDOWS +} + +// "foo/bar" == foo//bar" == "foo///bar" +TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) { + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", + FilePath("foo" GTEST_PATH_SEP_ "bar").string()); + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", + FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); + EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", + FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ + GTEST_PATH_SEP_ "bar").string()); +} + +// "/bar" == //bar" == "///bar" +TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) { + EXPECT_EQ(GTEST_PATH_SEP_ "bar", + FilePath(GTEST_PATH_SEP_ "bar").string()); + EXPECT_EQ(GTEST_PATH_SEP_ "bar", + FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); + EXPECT_EQ(GTEST_PATH_SEP_ "bar", + FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); +} + +// "foo/" == foo//" == "foo///" +TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) { + EXPECT_EQ("foo" GTEST_PATH_SEP_, + FilePath("foo" GTEST_PATH_SEP_).string()); + EXPECT_EQ("foo" GTEST_PATH_SEP_, + FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); + EXPECT_EQ("foo" GTEST_PATH_SEP_, + FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); +} + +#if GTEST_HAS_ALT_PATH_SEP_ + +// Tests that separators at the end of the string are normalized +// regardless of their combination (e.g. "foo\" =="foo/\" == +// "foo\\/"). +TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) { + EXPECT_EQ("foo" GTEST_PATH_SEP_, + FilePath("foo/").string()); + EXPECT_EQ("foo" GTEST_PATH_SEP_, + FilePath("foo" GTEST_PATH_SEP_ "/").string()); + EXPECT_EQ("foo" GTEST_PATH_SEP_, + FilePath("foo//" GTEST_PATH_SEP_).string()); +} + +#endif + +TEST(AssignmentOperatorTest, DefaultAssignedToNonDefault) { + FilePath default_path; + FilePath non_default_path("path"); + non_default_path = default_path; + EXPECT_EQ("", non_default_path.string()); + EXPECT_EQ("", default_path.string()); // RHS var is unchanged. +} + +TEST(AssignmentOperatorTest, NonDefaultAssignedToDefault) { + FilePath non_default_path("path"); + FilePath default_path; + default_path = non_default_path; + EXPECT_EQ("path", default_path.string()); + EXPECT_EQ("path", non_default_path.string()); // RHS var is unchanged. +} + +TEST(AssignmentOperatorTest, ConstAssignedToNonConst) { + const FilePath const_default_path("const_path"); + FilePath non_default_path("path"); + non_default_path = const_default_path; + EXPECT_EQ("const_path", non_default_path.string()); +} + +class DirectoryCreationTest : public Test { + protected: + virtual void SetUp() { + testdata_path_.Set(FilePath( + TempDir() + GetCurrentExecutableName().string() + + "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_)); + testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator()); + + unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), + 0, "txt")); + unique_file1_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), + 1, "txt")); + + remove(testdata_file_.c_str()); + remove(unique_file0_.c_str()); + remove(unique_file1_.c_str()); + posix::RmDir(testdata_path_.c_str()); + } + + virtual void TearDown() { + remove(testdata_file_.c_str()); + remove(unique_file0_.c_str()); + remove(unique_file1_.c_str()); + posix::RmDir(testdata_path_.c_str()); + } + + void CreateTextFile(const char* filename) { + FILE* f = posix::FOpen(filename, "w"); + fprintf(f, "text\n"); + fclose(f); + } + + // Strings representing a directory and a file, with identical paths + // except for the trailing separator character that distinquishes + // a directory named 'test' from a file named 'test'. Example names: + FilePath testdata_path_; // "/tmp/directory_creation/test/" + FilePath testdata_file_; // "/tmp/directory_creation/test" + FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt" + FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt" +}; + +TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) { + EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string(); + EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively()); + EXPECT_TRUE(testdata_path_.DirectoryExists()); +} + +TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) { + EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string(); + EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively()); + // Call 'create' again... should still succeed. + EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively()); +} + +TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) { + FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_, + FilePath("unique"), "txt")); + EXPECT_EQ(unique_file0_.string(), file_path.string()); + EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there + + testdata_path_.CreateDirectoriesRecursively(); + EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file still not there + CreateTextFile(file_path.c_str()); + EXPECT_TRUE(file_path.FileOrDirectoryExists()); + + FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_, + FilePath("unique"), "txt")); + EXPECT_EQ(unique_file1_.string(), file_path2.string()); + EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there + CreateTextFile(file_path2.c_str()); + EXPECT_TRUE(file_path2.FileOrDirectoryExists()); +} + +TEST_F(DirectoryCreationTest, CreateDirectoriesFail) { + // force a failure by putting a file where we will try to create a directory. + CreateTextFile(testdata_file_.c_str()); + EXPECT_TRUE(testdata_file_.FileOrDirectoryExists()); + EXPECT_FALSE(testdata_file_.DirectoryExists()); + EXPECT_FALSE(testdata_file_.CreateDirectoriesRecursively()); +} + +TEST(NoDirectoryCreationTest, CreateNoDirectoriesForDefaultXmlFile) { + const FilePath test_detail_xml("test_detail.xml"); + EXPECT_FALSE(test_detail_xml.CreateDirectoriesRecursively()); +} + +TEST(FilePathTest, DefaultConstructor) { + FilePath fp; + EXPECT_EQ("", fp.string()); +} + +TEST(FilePathTest, CharAndCopyConstructors) { + const FilePath fp("spicy"); + EXPECT_EQ("spicy", fp.string()); + + const FilePath fp_copy(fp); + EXPECT_EQ("spicy", fp_copy.string()); +} + +TEST(FilePathTest, StringConstructor) { + const FilePath fp(std::string("cider")); + EXPECT_EQ("cider", fp.string()); +} + +TEST(FilePathTest, Set) { + const FilePath apple("apple"); + FilePath mac("mac"); + mac.Set(apple); // Implement Set() since overloading operator= is forbidden. + EXPECT_EQ("apple", mac.string()); + EXPECT_EQ("apple", apple.string()); +} + +TEST(FilePathTest, ToString) { + const FilePath file("drink"); + EXPECT_EQ("drink", file.string()); +} + +TEST(FilePathTest, RemoveExtension) { + EXPECT_EQ("app", FilePath("app.cc").RemoveExtension("cc").string()); + EXPECT_EQ("app", FilePath("app.exe").RemoveExtension("exe").string()); + EXPECT_EQ("APP", FilePath("APP.EXE").RemoveExtension("exe").string()); +} + +TEST(FilePathTest, RemoveExtensionWhenThereIsNoExtension) { + EXPECT_EQ("app", FilePath("app").RemoveExtension("exe").string()); +} + +TEST(FilePathTest, IsDirectory) { + EXPECT_FALSE(FilePath("cola").IsDirectory()); + EXPECT_TRUE(FilePath("koala" GTEST_PATH_SEP_).IsDirectory()); +#if GTEST_HAS_ALT_PATH_SEP_ + EXPECT_TRUE(FilePath("koala/").IsDirectory()); +#endif +} + +TEST(FilePathTest, IsAbsolutePath) { + EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath()); + EXPECT_FALSE(FilePath("").IsAbsolutePath()); +#if GTEST_OS_WINDOWS + EXPECT_TRUE(FilePath("c:\\" GTEST_PATH_SEP_ "is_not" + GTEST_PATH_SEP_ "relative").IsAbsolutePath()); + EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath()); + EXPECT_TRUE(FilePath("c:/" GTEST_PATH_SEP_ "is_not" + GTEST_PATH_SEP_ "relative").IsAbsolutePath()); +#else + EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative") + .IsAbsolutePath()); +#endif // GTEST_OS_WINDOWS +} + +TEST(FilePathTest, IsRootDirectory) { +#if GTEST_OS_WINDOWS + EXPECT_TRUE(FilePath("a:\\").IsRootDirectory()); + EXPECT_TRUE(FilePath("Z:/").IsRootDirectory()); + EXPECT_TRUE(FilePath("e://").IsRootDirectory()); + EXPECT_FALSE(FilePath("").IsRootDirectory()); + EXPECT_FALSE(FilePath("b:").IsRootDirectory()); + EXPECT_FALSE(FilePath("b:a").IsRootDirectory()); + EXPECT_FALSE(FilePath("8:/").IsRootDirectory()); + EXPECT_FALSE(FilePath("c|/").IsRootDirectory()); +#else + EXPECT_TRUE(FilePath("/").IsRootDirectory()); + EXPECT_TRUE(FilePath("//").IsRootDirectory()); + EXPECT_FALSE(FilePath("").IsRootDirectory()); + EXPECT_FALSE(FilePath("\\").IsRootDirectory()); + EXPECT_FALSE(FilePath("/x").IsRootDirectory()); +#endif +} + +} // namespace +} // namespace internal +} // namespace testing diff --git a/googletest/test/googletest-json-outfiles-test.py b/googletest/test/googletest-json-outfiles-test.py new file mode 100644 index 0000000..46010d8 --- /dev/null +++ b/googletest/test/googletest-json-outfiles-test.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python +# Copyright 2018, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Unit test for the gtest_json_output module.""" + +import json +import os +import gtest_json_test_utils +import gtest_test_utils + +GTEST_OUTPUT_SUBDIR = 'json_outfiles' +GTEST_OUTPUT_1_TEST = 'gtest_xml_outfile1_test_' +GTEST_OUTPUT_2_TEST = 'gtest_xml_outfile2_test_' + +EXPECTED_1 = { + u'tests': 1, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'timestamp': u'*', + u'name': u'AllTests', + u'testsuites': [{ + u'name': u'PropertyOne', + u'tests': 1, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'testsuite': [{ + u'name': u'TestSomeProperties', + u'status': u'RUN', + u'time': u'*', + u'classname': u'PropertyOne', + u'SetUpProp': u'1', + u'TestSomeProperty': u'1', + u'TearDownProp': u'1', + }], + }], +} + +EXPECTED_2 = { + u'tests': 1, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'timestamp': u'*', + u'name': u'AllTests', + u'testsuites': [{ + u'name': u'PropertyTwo', + u'tests': 1, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'testsuite': [{ + u'name': u'TestSomeProperties', + u'status': u'RUN', + u'time': u'*', + u'classname': u'PropertyTwo', + u'SetUpProp': u'2', + u'TestSomeProperty': u'2', + u'TearDownProp': u'2', + }], + }], +} + + +class GTestJsonOutFilesTest(gtest_test_utils.TestCase): + """Unit test for Google Test's JSON output functionality.""" + + def setUp(self): + # We want the trailing '/' that the last "" provides in os.path.join, for + # telling Google Test to create an output directory instead of a single file + # for xml output. + self.output_dir_ = os.path.join(gtest_test_utils.GetTempDir(), + GTEST_OUTPUT_SUBDIR, '') + self.DeleteFilesAndDir() + + def tearDown(self): + self.DeleteFilesAndDir() + + def DeleteFilesAndDir(self): + try: + os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_1_TEST + '.json')) + except os.error: + pass + try: + os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_2_TEST + '.json')) + except os.error: + pass + try: + os.rmdir(self.output_dir_) + except os.error: + pass + + def testOutfile1(self): + self._TestOutFile(GTEST_OUTPUT_1_TEST, EXPECTED_1) + + def testOutfile2(self): + self._TestOutFile(GTEST_OUTPUT_2_TEST, EXPECTED_2) + + def _TestOutFile(self, test_name, expected): + gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name) + command = [gtest_prog_path, '--gtest_output=json:%s' % self.output_dir_] + p = gtest_test_utils.Subprocess(command, + working_dir=gtest_test_utils.GetTempDir()) + self.assert_(p.exited) + self.assertEquals(0, p.exit_code) + + # TODO(wan@google.com): libtool causes the built test binary to be + # named lt-gtest_xml_outfiles_test_ instead of + # gtest_xml_outfiles_test_. To account for this possibility, we + # allow both names in the following code. We should remove this + # hack when Chandler Carruth's libtool replacement tool is ready. + output_file_name1 = test_name + '.json' + output_file1 = os.path.join(self.output_dir_, output_file_name1) + output_file_name2 = 'lt-' + output_file_name1 + output_file2 = os.path.join(self.output_dir_, output_file_name2) + self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2), + output_file1) + + if os.path.isfile(output_file1): + with open(output_file1) as f: + actual = json.load(f) + else: + with open(output_file2) as f: + actual = json.load(f) + self.assertEqual(expected, gtest_json_test_utils.normalize(actual)) + + +if __name__ == '__main__': + os.environ['GTEST_STACK_TRACE_DEPTH'] = '0' + gtest_test_utils.Main() diff --git a/googletest/test/googletest-linked-ptr-test.cc b/googletest/test/googletest-linked-ptr-test.cc new file mode 100644 index 0000000..6fcf512 --- /dev/null +++ b/googletest/test/googletest-linked-ptr-test.cc @@ -0,0 +1,154 @@ +// Copyright 2003, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: Dan Egnor (egnor@google.com) +// Ported to Windows: Vadim Berman (vadimb@google.com) + +#include "gtest/internal/gtest-linked_ptr.h" + +#include +#include "gtest/gtest.h" + +namespace { + +using testing::Message; +using testing::internal::linked_ptr; + +int num; +Message* history = NULL; + +// Class which tracks allocation/deallocation +class A { + public: + A(): mynum(num++) { *history << "A" << mynum << " ctor\n"; } + virtual ~A() { *history << "A" << mynum << " dtor\n"; } + virtual void Use() { *history << "A" << mynum << " use\n"; } + protected: + int mynum; +}; + +// Subclass +class B : public A { + public: + B() { *history << "B" << mynum << " ctor\n"; } + ~B() { *history << "B" << mynum << " dtor\n"; } + virtual void Use() { *history << "B" << mynum << " use\n"; } +}; + +class LinkedPtrTest : public testing::Test { + public: + LinkedPtrTest() { + num = 0; + history = new Message; + } + + virtual ~LinkedPtrTest() { + delete history; + history = NULL; + } +}; + +TEST_F(LinkedPtrTest, GeneralTest) { + { + linked_ptr a0, a1, a2; + // Use explicit function call notation here to suppress self-assign warning. + a0.operator=(a0); + a1 = a2; + ASSERT_EQ(a0.get(), static_cast(NULL)); + ASSERT_EQ(a1.get(), static_cast(NULL)); + ASSERT_EQ(a2.get(), static_cast(NULL)); + ASSERT_TRUE(a0 == NULL); + ASSERT_TRUE(a1 == NULL); + ASSERT_TRUE(a2 == NULL); + + { + linked_ptr a3(new A); + a0 = a3; + ASSERT_TRUE(a0 == a3); + ASSERT_TRUE(a0 != NULL); + ASSERT_TRUE(a0.get() == a3); + ASSERT_TRUE(a0 == a3.get()); + linked_ptr a4(a0); + a1 = a4; + linked_ptr a5(new A); + ASSERT_TRUE(a5.get() != a3); + ASSERT_TRUE(a5 != a3.get()); + a2 = a5; + linked_ptr b0(new B); + linked_ptr a6(b0); + ASSERT_TRUE(b0 == a6); + ASSERT_TRUE(a6 == b0); + ASSERT_TRUE(b0 != NULL); + a5 = b0; + a5 = b0; + a3->Use(); + a4->Use(); + a5->Use(); + a6->Use(); + b0->Use(); + (*b0).Use(); + b0.get()->Use(); + } + + a0->Use(); + a1->Use(); + a2->Use(); + + a1 = a2; + a2.reset(new A); + a0.reset(); + + linked_ptr a7; + } + + ASSERT_STREQ( + "A0 ctor\n" + "A1 ctor\n" + "A2 ctor\n" + "B2 ctor\n" + "A0 use\n" + "A0 use\n" + "B2 use\n" + "B2 use\n" + "B2 use\n" + "B2 use\n" + "B2 use\n" + "B2 dtor\n" + "A2 dtor\n" + "A0 use\n" + "A0 use\n" + "A1 use\n" + "A3 ctor\n" + "A0 dtor\n" + "A3 dtor\n" + "A1 dtor\n", + history->GetString().c_str()); +} + +} // Unnamed namespace diff --git a/googletest/test/gtest-filepath_test.cc b/googletest/test/gtest-filepath_test.cc deleted file mode 100644 index 29cea3d..0000000 --- a/googletest/test/gtest-filepath_test.cc +++ /dev/null @@ -1,652 +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. -// -// -// Google Test filepath utilities -// -// This file tests classes and functions used internally by -// Google Test. They are subject to change without notice. -// -// This file is #included from gtest-internal.h. -// Do not #include this file anywhere else! - -#include "gtest/internal/gtest-filepath.h" -#include "gtest/gtest.h" -#include "src/gtest-internal-inl.h" - -#if GTEST_OS_WINDOWS_MOBILE -# include // NOLINT -#elif GTEST_OS_WINDOWS -# include // NOLINT -#endif // GTEST_OS_WINDOWS_MOBILE - -namespace testing { -namespace internal { -namespace { - -#if GTEST_OS_WINDOWS_MOBILE -// TODO(wan@google.com): Move these to the POSIX adapter section in -// gtest-port.h. - -// Windows CE doesn't have the remove C function. -int remove(const char* path) { - LPCWSTR wpath = String::AnsiToUtf16(path); - int ret = DeleteFile(wpath) ? 0 : -1; - delete [] wpath; - return ret; -} -// Windows CE doesn't have the _rmdir C function. -int _rmdir(const char* path) { - FilePath filepath(path); - LPCWSTR wpath = String::AnsiToUtf16( - filepath.RemoveTrailingPathSeparator().c_str()); - int ret = RemoveDirectory(wpath) ? 0 : -1; - delete [] wpath; - return ret; -} - -#else - -TEST(GetCurrentDirTest, ReturnsCurrentDir) { - const FilePath original_dir = FilePath::GetCurrentDir(); - EXPECT_FALSE(original_dir.IsEmpty()); - - posix::ChDir(GTEST_PATH_SEP_); - const FilePath cwd = FilePath::GetCurrentDir(); - posix::ChDir(original_dir.c_str()); - -# if GTEST_OS_WINDOWS - - // Skips the ":". - const char* const cwd_without_drive = strchr(cwd.c_str(), ':'); - ASSERT_TRUE(cwd_without_drive != NULL); - EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1); - -# else - - EXPECT_EQ(GTEST_PATH_SEP_, cwd.string()); - -# endif -} - -#endif // GTEST_OS_WINDOWS_MOBILE - -TEST(IsEmptyTest, ReturnsTrueForEmptyPath) { - EXPECT_TRUE(FilePath("").IsEmpty()); -} - -TEST(IsEmptyTest, ReturnsFalseForNonEmptyPath) { - EXPECT_FALSE(FilePath("a").IsEmpty()); - EXPECT_FALSE(FilePath(".").IsEmpty()); - EXPECT_FALSE(FilePath("a/b").IsEmpty()); - EXPECT_FALSE(FilePath("a\\b\\").IsEmpty()); -} - -// RemoveDirectoryName "" -> "" -TEST(RemoveDirectoryNameTest, WhenEmptyName) { - EXPECT_EQ("", FilePath("").RemoveDirectoryName().string()); -} - -// RemoveDirectoryName "afile" -> "afile" -TEST(RemoveDirectoryNameTest, ButNoDirectory) { - EXPECT_EQ("afile", - FilePath("afile").RemoveDirectoryName().string()); -} - -// RemoveDirectoryName "/afile" -> "afile" -TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) { - EXPECT_EQ("afile", - FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); -} - -// RemoveDirectoryName "adir/" -> "" -TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) { - EXPECT_EQ("", - FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string()); -} - -// RemoveDirectoryName "adir/afile" -> "afile" -TEST(RemoveDirectoryNameTest, ShouldGiveFileName) { - EXPECT_EQ("afile", - FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string()); -} - -// RemoveDirectoryName "adir/subdir/afile" -> "afile" -TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) { - EXPECT_EQ("afile", - FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") - .RemoveDirectoryName().string()); -} - -#if GTEST_HAS_ALT_PATH_SEP_ - -// Tests that RemoveDirectoryName() works with the alternate separator -// on Windows. - -// RemoveDirectoryName("/afile") -> "afile" -TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileNameForAlternateSeparator) { - EXPECT_EQ("afile", FilePath("/afile").RemoveDirectoryName().string()); -} - -// RemoveDirectoryName("adir/") -> "" -TEST(RemoveDirectoryNameTest, WhereThereIsNoFileNameForAlternateSeparator) { - EXPECT_EQ("", FilePath("adir/").RemoveDirectoryName().string()); -} - -// RemoveDirectoryName("adir/afile") -> "afile" -TEST(RemoveDirectoryNameTest, ShouldGiveFileNameForAlternateSeparator) { - EXPECT_EQ("afile", FilePath("adir/afile").RemoveDirectoryName().string()); -} - -// RemoveDirectoryName("adir/subdir/afile") -> "afile" -TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileNameForAlternateSeparator) { - EXPECT_EQ("afile", - FilePath("adir/subdir/afile").RemoveDirectoryName().string()); -} - -#endif - -// RemoveFileName "" -> "./" -TEST(RemoveFileNameTest, EmptyName) { -#if GTEST_OS_WINDOWS_MOBILE - // On Windows CE, we use the root as the current directory. - EXPECT_EQ(GTEST_PATH_SEP_, FilePath("").RemoveFileName().string()); -#else - EXPECT_EQ("." GTEST_PATH_SEP_, FilePath("").RemoveFileName().string()); -#endif -} - -// RemoveFileName "adir/" -> "adir/" -TEST(RemoveFileNameTest, ButNoFile) { - EXPECT_EQ("adir" GTEST_PATH_SEP_, - FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string()); -} - -// RemoveFileName "adir/afile" -> "adir/" -TEST(RemoveFileNameTest, GivesDirName) { - EXPECT_EQ("adir" GTEST_PATH_SEP_, - FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveFileName().string()); -} - -// RemoveFileName "adir/subdir/afile" -> "adir/subdir/" -TEST(RemoveFileNameTest, GivesDirAndSubDirName) { - EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_, - FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile") - .RemoveFileName().string()); -} - -// RemoveFileName "/afile" -> "/" -TEST(RemoveFileNameTest, GivesRootDir) { - EXPECT_EQ(GTEST_PATH_SEP_, - FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string()); -} - -#if GTEST_HAS_ALT_PATH_SEP_ - -// Tests that RemoveFileName() works with the alternate separator on -// Windows. - -// RemoveFileName("adir/") -> "adir/" -TEST(RemoveFileNameTest, ButNoFileForAlternateSeparator) { - EXPECT_EQ("adir" GTEST_PATH_SEP_, - FilePath("adir/").RemoveFileName().string()); -} - -// RemoveFileName("adir/afile") -> "adir/" -TEST(RemoveFileNameTest, GivesDirNameForAlternateSeparator) { - EXPECT_EQ("adir" GTEST_PATH_SEP_, - FilePath("adir/afile").RemoveFileName().string()); -} - -// RemoveFileName("adir/subdir/afile") -> "adir/subdir/" -TEST(RemoveFileNameTest, GivesDirAndSubDirNameForAlternateSeparator) { - EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_, - FilePath("adir/subdir/afile").RemoveFileName().string()); -} - -// RemoveFileName("/afile") -> "\" -TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) { - EXPECT_EQ(GTEST_PATH_SEP_, FilePath("/afile").RemoveFileName().string()); -} - -#endif - -TEST(MakeFileNameTest, GenerateWhenNumberIsZero) { - FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), - 0, "xml"); - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); -} - -TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) { - FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), - 12, "xml"); - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string()); -} - -TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) { - FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), - FilePath("bar"), 0, "xml"); - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); -} - -TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) { - FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_), - FilePath("bar"), 12, "xml"); - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string()); -} - -TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) { - FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), - 0, "xml"); - EXPECT_EQ("bar.xml", actual.string()); -} - -TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) { - FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"), - 14, "xml"); - EXPECT_EQ("bar_14.xml", actual.string()); -} - -TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) { - FilePath actual = FilePath::ConcatPaths(FilePath("foo"), - FilePath("bar.xml")); - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); -} - -TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) { - FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_), - FilePath("bar.xml")); - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string()); -} - -TEST(ConcatPathsTest, Path1BeingEmpty) { - FilePath actual = FilePath::ConcatPaths(FilePath(""), - FilePath("bar.xml")); - EXPECT_EQ("bar.xml", actual.string()); -} - -TEST(ConcatPathsTest, Path2BeingEmpty) { - FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath("")); - EXPECT_EQ("foo" GTEST_PATH_SEP_, actual.string()); -} - -TEST(ConcatPathsTest, BothPathBeingEmpty) { - FilePath actual = FilePath::ConcatPaths(FilePath(""), - FilePath("")); - EXPECT_EQ("", actual.string()); -} - -TEST(ConcatPathsTest, Path1ContainsPathSep) { - FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_ "bar"), - FilePath("foobar.xml")); - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "foobar.xml", - actual.string()); -} - -TEST(ConcatPathsTest, Path2ContainsPathSep) { - FilePath actual = FilePath::ConcatPaths( - FilePath("foo" GTEST_PATH_SEP_), - FilePath("bar" GTEST_PATH_SEP_ "bar.xml")); - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml", - actual.string()); -} - -TEST(ConcatPathsTest, Path2EndsWithPathSep) { - FilePath actual = FilePath::ConcatPaths(FilePath("foo"), - FilePath("bar" GTEST_PATH_SEP_)); - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string()); -} - -// RemoveTrailingPathSeparator "" -> "" -TEST(RemoveTrailingPathSeparatorTest, EmptyString) { - EXPECT_EQ("", FilePath("").RemoveTrailingPathSeparator().string()); -} - -// RemoveTrailingPathSeparator "foo" -> "foo" -TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) { - EXPECT_EQ("foo", FilePath("foo").RemoveTrailingPathSeparator().string()); -} - -// RemoveTrailingPathSeparator "foo/" -> "foo" -TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) { - EXPECT_EQ("foo", - FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string()); -#if GTEST_HAS_ALT_PATH_SEP_ - EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string()); -#endif -} - -// RemoveTrailingPathSeparator "foo/bar/" -> "foo/bar/" -TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) { - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", - FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_) - .RemoveTrailingPathSeparator().string()); -} - -// RemoveTrailingPathSeparator "foo/bar" -> "foo/bar" -TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) { - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", - FilePath("foo" GTEST_PATH_SEP_ "bar") - .RemoveTrailingPathSeparator().string()); -} - -TEST(DirectoryTest, RootDirectoryExists) { -#if GTEST_OS_WINDOWS // We are on Windows. - char current_drive[_MAX_PATH]; // NOLINT - current_drive[0] = static_cast(_getdrive() + 'A' - 1); - current_drive[1] = ':'; - current_drive[2] = '\\'; - current_drive[3] = '\0'; - EXPECT_TRUE(FilePath(current_drive).DirectoryExists()); -#else - EXPECT_TRUE(FilePath("/").DirectoryExists()); -#endif // GTEST_OS_WINDOWS -} - -#if GTEST_OS_WINDOWS -TEST(DirectoryTest, RootOfWrongDriveDoesNotExists) { - const int saved_drive_ = _getdrive(); - // Find a drive that doesn't exist. Start with 'Z' to avoid common ones. - for (char drive = 'Z'; drive >= 'A'; drive--) - if (_chdrive(drive - 'A' + 1) == -1) { - char non_drive[_MAX_PATH]; // NOLINT - non_drive[0] = drive; - non_drive[1] = ':'; - non_drive[2] = '\\'; - non_drive[3] = '\0'; - EXPECT_FALSE(FilePath(non_drive).DirectoryExists()); - break; - } - _chdrive(saved_drive_); -} -#endif // GTEST_OS_WINDOWS - -#if !GTEST_OS_WINDOWS_MOBILE -// Windows CE _does_ consider an empty directory to exist. -TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) { - EXPECT_FALSE(FilePath("").DirectoryExists()); -} -#endif // !GTEST_OS_WINDOWS_MOBILE - -TEST(DirectoryTest, CurrentDirectoryExists) { -#if GTEST_OS_WINDOWS // We are on Windows. -# ifndef _WIN32_CE // Windows CE doesn't have a current directory. - - EXPECT_TRUE(FilePath(".").DirectoryExists()); - EXPECT_TRUE(FilePath(".\\").DirectoryExists()); - -# endif // _WIN32_CE -#else - EXPECT_TRUE(FilePath(".").DirectoryExists()); - EXPECT_TRUE(FilePath("./").DirectoryExists()); -#endif // GTEST_OS_WINDOWS -} - -// "foo/bar" == foo//bar" == "foo///bar" -TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) { - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", - FilePath("foo" GTEST_PATH_SEP_ "bar").string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", - FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", - FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ - GTEST_PATH_SEP_ "bar").string()); -} - -// "/bar" == //bar" == "///bar" -TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) { - EXPECT_EQ(GTEST_PATH_SEP_ "bar", - FilePath(GTEST_PATH_SEP_ "bar").string()); - EXPECT_EQ(GTEST_PATH_SEP_ "bar", - FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); - EXPECT_EQ(GTEST_PATH_SEP_ "bar", - FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string()); -} - -// "foo/" == foo//" == "foo///" -TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) { - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo" GTEST_PATH_SEP_).string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string()); -} - -#if GTEST_HAS_ALT_PATH_SEP_ - -// Tests that separators at the end of the string are normalized -// regardless of their combination (e.g. "foo\" =="foo/\" == -// "foo\\/"). -TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) { - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo/").string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo" GTEST_PATH_SEP_ "/").string()); - EXPECT_EQ("foo" GTEST_PATH_SEP_, - FilePath("foo//" GTEST_PATH_SEP_).string()); -} - -#endif - -TEST(AssignmentOperatorTest, DefaultAssignedToNonDefault) { - FilePath default_path; - FilePath non_default_path("path"); - non_default_path = default_path; - EXPECT_EQ("", non_default_path.string()); - EXPECT_EQ("", default_path.string()); // RHS var is unchanged. -} - -TEST(AssignmentOperatorTest, NonDefaultAssignedToDefault) { - FilePath non_default_path("path"); - FilePath default_path; - default_path = non_default_path; - EXPECT_EQ("path", default_path.string()); - EXPECT_EQ("path", non_default_path.string()); // RHS var is unchanged. -} - -TEST(AssignmentOperatorTest, ConstAssignedToNonConst) { - const FilePath const_default_path("const_path"); - FilePath non_default_path("path"); - non_default_path = const_default_path; - EXPECT_EQ("const_path", non_default_path.string()); -} - -class DirectoryCreationTest : public Test { - protected: - virtual void SetUp() { - testdata_path_.Set(FilePath( - TempDir() + GetCurrentExecutableName().string() + - "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_)); - testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator()); - - unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), - 0, "txt")); - unique_file1_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"), - 1, "txt")); - - remove(testdata_file_.c_str()); - remove(unique_file0_.c_str()); - remove(unique_file1_.c_str()); - posix::RmDir(testdata_path_.c_str()); - } - - virtual void TearDown() { - remove(testdata_file_.c_str()); - remove(unique_file0_.c_str()); - remove(unique_file1_.c_str()); - posix::RmDir(testdata_path_.c_str()); - } - - void CreateTextFile(const char* filename) { - FILE* f = posix::FOpen(filename, "w"); - fprintf(f, "text\n"); - fclose(f); - } - - // Strings representing a directory and a file, with identical paths - // except for the trailing separator character that distinquishes - // a directory named 'test' from a file named 'test'. Example names: - FilePath testdata_path_; // "/tmp/directory_creation/test/" - FilePath testdata_file_; // "/tmp/directory_creation/test" - FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt" - FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt" -}; - -TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) { - EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string(); - EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively()); - EXPECT_TRUE(testdata_path_.DirectoryExists()); -} - -TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) { - EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string(); - EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively()); - // Call 'create' again... should still succeed. - EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively()); -} - -TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) { - FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_, - FilePath("unique"), "txt")); - EXPECT_EQ(unique_file0_.string(), file_path.string()); - EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there - - testdata_path_.CreateDirectoriesRecursively(); - EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file still not there - CreateTextFile(file_path.c_str()); - EXPECT_TRUE(file_path.FileOrDirectoryExists()); - - FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_, - FilePath("unique"), "txt")); - EXPECT_EQ(unique_file1_.string(), file_path2.string()); - EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there - CreateTextFile(file_path2.c_str()); - EXPECT_TRUE(file_path2.FileOrDirectoryExists()); -} - -TEST_F(DirectoryCreationTest, CreateDirectoriesFail) { - // force a failure by putting a file where we will try to create a directory. - CreateTextFile(testdata_file_.c_str()); - EXPECT_TRUE(testdata_file_.FileOrDirectoryExists()); - EXPECT_FALSE(testdata_file_.DirectoryExists()); - EXPECT_FALSE(testdata_file_.CreateDirectoriesRecursively()); -} - -TEST(NoDirectoryCreationTest, CreateNoDirectoriesForDefaultXmlFile) { - const FilePath test_detail_xml("test_detail.xml"); - EXPECT_FALSE(test_detail_xml.CreateDirectoriesRecursively()); -} - -TEST(FilePathTest, DefaultConstructor) { - FilePath fp; - EXPECT_EQ("", fp.string()); -} - -TEST(FilePathTest, CharAndCopyConstructors) { - const FilePath fp("spicy"); - EXPECT_EQ("spicy", fp.string()); - - const FilePath fp_copy(fp); - EXPECT_EQ("spicy", fp_copy.string()); -} - -TEST(FilePathTest, StringConstructor) { - const FilePath fp(std::string("cider")); - EXPECT_EQ("cider", fp.string()); -} - -TEST(FilePathTest, Set) { - const FilePath apple("apple"); - FilePath mac("mac"); - mac.Set(apple); // Implement Set() since overloading operator= is forbidden. - EXPECT_EQ("apple", mac.string()); - EXPECT_EQ("apple", apple.string()); -} - -TEST(FilePathTest, ToString) { - const FilePath file("drink"); - EXPECT_EQ("drink", file.string()); -} - -TEST(FilePathTest, RemoveExtension) { - EXPECT_EQ("app", FilePath("app.cc").RemoveExtension("cc").string()); - EXPECT_EQ("app", FilePath("app.exe").RemoveExtension("exe").string()); - EXPECT_EQ("APP", FilePath("APP.EXE").RemoveExtension("exe").string()); -} - -TEST(FilePathTest, RemoveExtensionWhenThereIsNoExtension) { - EXPECT_EQ("app", FilePath("app").RemoveExtension("exe").string()); -} - -TEST(FilePathTest, IsDirectory) { - EXPECT_FALSE(FilePath("cola").IsDirectory()); - EXPECT_TRUE(FilePath("koala" GTEST_PATH_SEP_).IsDirectory()); -#if GTEST_HAS_ALT_PATH_SEP_ - EXPECT_TRUE(FilePath("koala/").IsDirectory()); -#endif -} - -TEST(FilePathTest, IsAbsolutePath) { - EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath()); - EXPECT_FALSE(FilePath("").IsAbsolutePath()); -#if GTEST_OS_WINDOWS - EXPECT_TRUE(FilePath("c:\\" GTEST_PATH_SEP_ "is_not" - GTEST_PATH_SEP_ "relative").IsAbsolutePath()); - EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath()); - EXPECT_TRUE(FilePath("c:/" GTEST_PATH_SEP_ "is_not" - GTEST_PATH_SEP_ "relative").IsAbsolutePath()); -#else - EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative") - .IsAbsolutePath()); -#endif // GTEST_OS_WINDOWS -} - -TEST(FilePathTest, IsRootDirectory) { -#if GTEST_OS_WINDOWS - EXPECT_TRUE(FilePath("a:\\").IsRootDirectory()); - EXPECT_TRUE(FilePath("Z:/").IsRootDirectory()); - EXPECT_TRUE(FilePath("e://").IsRootDirectory()); - EXPECT_FALSE(FilePath("").IsRootDirectory()); - EXPECT_FALSE(FilePath("b:").IsRootDirectory()); - EXPECT_FALSE(FilePath("b:a").IsRootDirectory()); - EXPECT_FALSE(FilePath("8:/").IsRootDirectory()); - EXPECT_FALSE(FilePath("c|/").IsRootDirectory()); -#else - EXPECT_TRUE(FilePath("/").IsRootDirectory()); - EXPECT_TRUE(FilePath("//").IsRootDirectory()); - EXPECT_FALSE(FilePath("").IsRootDirectory()); - EXPECT_FALSE(FilePath("\\").IsRootDirectory()); - EXPECT_FALSE(FilePath("/x").IsRootDirectory()); -#endif -} - -} // namespace -} // namespace internal -} // namespace testing diff --git a/googletest/test/gtest-linked_ptr_test.cc b/googletest/test/gtest-linked_ptr_test.cc deleted file mode 100644 index 6fcf512..0000000 --- a/googletest/test/gtest-linked_ptr_test.cc +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2003, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Authors: Dan Egnor (egnor@google.com) -// Ported to Windows: Vadim Berman (vadimb@google.com) - -#include "gtest/internal/gtest-linked_ptr.h" - -#include -#include "gtest/gtest.h" - -namespace { - -using testing::Message; -using testing::internal::linked_ptr; - -int num; -Message* history = NULL; - -// Class which tracks allocation/deallocation -class A { - public: - A(): mynum(num++) { *history << "A" << mynum << " ctor\n"; } - virtual ~A() { *history << "A" << mynum << " dtor\n"; } - virtual void Use() { *history << "A" << mynum << " use\n"; } - protected: - int mynum; -}; - -// Subclass -class B : public A { - public: - B() { *history << "B" << mynum << " ctor\n"; } - ~B() { *history << "B" << mynum << " dtor\n"; } - virtual void Use() { *history << "B" << mynum << " use\n"; } -}; - -class LinkedPtrTest : public testing::Test { - public: - LinkedPtrTest() { - num = 0; - history = new Message; - } - - virtual ~LinkedPtrTest() { - delete history; - history = NULL; - } -}; - -TEST_F(LinkedPtrTest, GeneralTest) { - { - linked_ptr a0, a1, a2; - // Use explicit function call notation here to suppress self-assign warning. - a0.operator=(a0); - a1 = a2; - ASSERT_EQ(a0.get(), static_cast(NULL)); - ASSERT_EQ(a1.get(), static_cast(NULL)); - ASSERT_EQ(a2.get(), static_cast(NULL)); - ASSERT_TRUE(a0 == NULL); - ASSERT_TRUE(a1 == NULL); - ASSERT_TRUE(a2 == NULL); - - { - linked_ptr a3(new A); - a0 = a3; - ASSERT_TRUE(a0 == a3); - ASSERT_TRUE(a0 != NULL); - ASSERT_TRUE(a0.get() == a3); - ASSERT_TRUE(a0 == a3.get()); - linked_ptr a4(a0); - a1 = a4; - linked_ptr a5(new A); - ASSERT_TRUE(a5.get() != a3); - ASSERT_TRUE(a5 != a3.get()); - a2 = a5; - linked_ptr b0(new B); - linked_ptr a6(b0); - ASSERT_TRUE(b0 == a6); - ASSERT_TRUE(a6 == b0); - ASSERT_TRUE(b0 != NULL); - a5 = b0; - a5 = b0; - a3->Use(); - a4->Use(); - a5->Use(); - a6->Use(); - b0->Use(); - (*b0).Use(); - b0.get()->Use(); - } - - a0->Use(); - a1->Use(); - a2->Use(); - - a1 = a2; - a2.reset(new A); - a0.reset(); - - linked_ptr a7; - } - - ASSERT_STREQ( - "A0 ctor\n" - "A1 ctor\n" - "A2 ctor\n" - "B2 ctor\n" - "A0 use\n" - "A0 use\n" - "B2 use\n" - "B2 use\n" - "B2 use\n" - "B2 use\n" - "B2 use\n" - "B2 dtor\n" - "A2 dtor\n" - "A0 use\n" - "A0 use\n" - "A1 use\n" - "A3 ctor\n" - "A0 dtor\n" - "A3 dtor\n" - "A1 dtor\n", - history->GetString().c_str()); -} - -} // Unnamed namespace diff --git a/googletest/test/gtest-listener_test.cc b/googletest/test/gtest-listener_test.cc deleted file mode 100644 index 639529c..0000000 --- a/googletest/test/gtest-listener_test.cc +++ /dev/null @@ -1,311 +0,0 @@ -// Copyright 2009 Google Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: vladl@google.com (Vlad Losev) -// -// The Google C++ Testing and Mocking Framework (Google Test) -// -// This file verifies Google Test event listeners receive events at the -// right times. - -#include "gtest/gtest.h" -#include - -using ::testing::AddGlobalTestEnvironment; -using ::testing::Environment; -using ::testing::InitGoogleTest; -using ::testing::Test; -using ::testing::TestCase; -using ::testing::TestEventListener; -using ::testing::TestInfo; -using ::testing::TestPartResult; -using ::testing::UnitTest; - -// Used by tests to register their events. -std::vector* g_events = NULL; - -namespace testing { -namespace internal { - -class EventRecordingListener : public TestEventListener { - public: - explicit EventRecordingListener(const char* name) : name_(name) {} - - protected: - virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) { - g_events->push_back(GetFullMethodName("OnTestProgramStart")); - } - - virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, - int iteration) { - Message message; - message << GetFullMethodName("OnTestIterationStart") - << "(" << iteration << ")"; - g_events->push_back(message.GetString()); - } - - virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) { - g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpStart")); - } - - virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) { - g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpEnd")); - } - - virtual void OnTestCaseStart(const TestCase& /*test_case*/) { - g_events->push_back(GetFullMethodName("OnTestCaseStart")); - } - - virtual void OnTestStart(const TestInfo& /*test_info*/) { - g_events->push_back(GetFullMethodName("OnTestStart")); - } - - virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) { - g_events->push_back(GetFullMethodName("OnTestPartResult")); - } - - virtual void OnTestEnd(const TestInfo& /*test_info*/) { - g_events->push_back(GetFullMethodName("OnTestEnd")); - } - - virtual void OnTestCaseEnd(const TestCase& /*test_case*/) { - g_events->push_back(GetFullMethodName("OnTestCaseEnd")); - } - - virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) { - g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownStart")); - } - - virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) { - g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownEnd")); - } - - virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, - int iteration) { - Message message; - message << GetFullMethodName("OnTestIterationEnd") - << "(" << iteration << ")"; - g_events->push_back(message.GetString()); - } - - virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) { - g_events->push_back(GetFullMethodName("OnTestProgramEnd")); - } - - private: - std::string GetFullMethodName(const char* name) { - return name_ + "." + name; - } - - std::string name_; -}; - -class EnvironmentInvocationCatcher : public Environment { - protected: - virtual void SetUp() { - g_events->push_back("Environment::SetUp"); - } - - virtual void TearDown() { - g_events->push_back("Environment::TearDown"); - } -}; - -class ListenerTest : public Test { - protected: - static void SetUpTestCase() { - g_events->push_back("ListenerTest::SetUpTestCase"); - } - - static void TearDownTestCase() { - g_events->push_back("ListenerTest::TearDownTestCase"); - } - - virtual void SetUp() { - g_events->push_back("ListenerTest::SetUp"); - } - - virtual void TearDown() { - g_events->push_back("ListenerTest::TearDown"); - } -}; - -TEST_F(ListenerTest, DoesFoo) { - // Test execution order within a test case is not guaranteed so we are not - // recording the test name. - g_events->push_back("ListenerTest::* Test Body"); - SUCCEED(); // Triggers OnTestPartResult. -} - -TEST_F(ListenerTest, DoesBar) { - g_events->push_back("ListenerTest::* Test Body"); - SUCCEED(); // Triggers OnTestPartResult. -} - -} // namespace internal - -} // namespace testing - -using ::testing::internal::EnvironmentInvocationCatcher; -using ::testing::internal::EventRecordingListener; - -void VerifyResults(const std::vector& data, - const char* const* expected_data, - size_t expected_data_size) { - const size_t actual_size = data.size(); - // If the following assertion fails, a new entry will be appended to - // data. Hence we save data.size() first. - EXPECT_EQ(expected_data_size, actual_size); - - // Compares the common prefix. - const size_t shorter_size = expected_data_size <= actual_size ? - expected_data_size : actual_size; - size_t i = 0; - for (; i < shorter_size; ++i) { - ASSERT_STREQ(expected_data[i], data[i].c_str()) - << "at position " << i; - } - - // Prints extra elements in the actual data. - for (; i < actual_size; ++i) { - printf(" Actual event #%lu: %s\n", - static_cast(i), data[i].c_str()); - } -} - -int main(int argc, char **argv) { - std::vector events; - g_events = &events; - InitGoogleTest(&argc, argv); - - UnitTest::GetInstance()->listeners().Append( - new EventRecordingListener("1st")); - UnitTest::GetInstance()->listeners().Append( - new EventRecordingListener("2nd")); - - AddGlobalTestEnvironment(new EnvironmentInvocationCatcher); - - GTEST_CHECK_(events.size() == 0) - << "AddGlobalTestEnvironment should not generate any events itself."; - - ::testing::GTEST_FLAG(repeat) = 2; - int ret_val = RUN_ALL_TESTS(); - - const char* const expected_events[] = { - "1st.OnTestProgramStart", - "2nd.OnTestProgramStart", - "1st.OnTestIterationStart(0)", - "2nd.OnTestIterationStart(0)", - "1st.OnEnvironmentsSetUpStart", - "2nd.OnEnvironmentsSetUpStart", - "Environment::SetUp", - "2nd.OnEnvironmentsSetUpEnd", - "1st.OnEnvironmentsSetUpEnd", - "1st.OnTestCaseStart", - "2nd.OnTestCaseStart", - "ListenerTest::SetUpTestCase", - "1st.OnTestStart", - "2nd.OnTestStart", - "ListenerTest::SetUp", - "ListenerTest::* Test Body", - "1st.OnTestPartResult", - "2nd.OnTestPartResult", - "ListenerTest::TearDown", - "2nd.OnTestEnd", - "1st.OnTestEnd", - "1st.OnTestStart", - "2nd.OnTestStart", - "ListenerTest::SetUp", - "ListenerTest::* Test Body", - "1st.OnTestPartResult", - "2nd.OnTestPartResult", - "ListenerTest::TearDown", - "2nd.OnTestEnd", - "1st.OnTestEnd", - "ListenerTest::TearDownTestCase", - "2nd.OnTestCaseEnd", - "1st.OnTestCaseEnd", - "1st.OnEnvironmentsTearDownStart", - "2nd.OnEnvironmentsTearDownStart", - "Environment::TearDown", - "2nd.OnEnvironmentsTearDownEnd", - "1st.OnEnvironmentsTearDownEnd", - "2nd.OnTestIterationEnd(0)", - "1st.OnTestIterationEnd(0)", - "1st.OnTestIterationStart(1)", - "2nd.OnTestIterationStart(1)", - "1st.OnEnvironmentsSetUpStart", - "2nd.OnEnvironmentsSetUpStart", - "Environment::SetUp", - "2nd.OnEnvironmentsSetUpEnd", - "1st.OnEnvironmentsSetUpEnd", - "1st.OnTestCaseStart", - "2nd.OnTestCaseStart", - "ListenerTest::SetUpTestCase", - "1st.OnTestStart", - "2nd.OnTestStart", - "ListenerTest::SetUp", - "ListenerTest::* Test Body", - "1st.OnTestPartResult", - "2nd.OnTestPartResult", - "ListenerTest::TearDown", - "2nd.OnTestEnd", - "1st.OnTestEnd", - "1st.OnTestStart", - "2nd.OnTestStart", - "ListenerTest::SetUp", - "ListenerTest::* Test Body", - "1st.OnTestPartResult", - "2nd.OnTestPartResult", - "ListenerTest::TearDown", - "2nd.OnTestEnd", - "1st.OnTestEnd", - "ListenerTest::TearDownTestCase", - "2nd.OnTestCaseEnd", - "1st.OnTestCaseEnd", - "1st.OnEnvironmentsTearDownStart", - "2nd.OnEnvironmentsTearDownStart", - "Environment::TearDown", - "2nd.OnEnvironmentsTearDownEnd", - "1st.OnEnvironmentsTearDownEnd", - "2nd.OnTestIterationEnd(1)", - "1st.OnTestIterationEnd(1)", - "2nd.OnTestProgramEnd", - "1st.OnTestProgramEnd" - }; - VerifyResults(events, - expected_events, - sizeof(expected_events)/sizeof(expected_events[0])); - - // We need to check manually for ad hoc test failures that happen after - // RUN_ALL_TESTS finishes. - if (UnitTest::GetInstance()->Failed()) - ret_val = 1; - - return ret_val; -} -- cgit v0.12 From 7001dff4fc23f96170402fc409ae0cb0c62ac637 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 16:12:09 -0400 Subject: adding googletest-json-output unitest --- googletest/test/BUILD.bazel | 21 + googletest/test/googletest-json-output-unittest.py | 618 +++++++++++++++++++++ 2 files changed, 639 insertions(+) create mode 100644 googletest/test/googletest-json-output-unittest.py diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index fdec685..7d0932b 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -449,6 +449,7 @@ py_test( deps = [":gtest_test_utils"], ) + py_test( name = "googletest-json-outfiles-test", size = "small", @@ -462,3 +463,23 @@ py_test( ], deps = [":gtest_test_utils"], ) + +py_test( + name = "googletest-json-output-unittest", + size = "medium", + srcs = [ + "googletest-json-output-unittest.py", + "gtest_json_test_utils.py", + ], + data = [ + # We invoke gtest_no_test_unittest to verify the JSON output + # when the test program contains no test definition. + ":gtest_no_test_unittest", + ":gtest_xml_output_unittest_", + ], + args = select({ + ":has_absl": [], + "//conditions:default": ["--no_stacktrace_support"], + }), + deps = [":gtest_test_utils"], +) diff --git a/googletest/test/googletest-json-output-unittest.py b/googletest/test/googletest-json-output-unittest.py new file mode 100644 index 0000000..57dcd5f --- /dev/null +++ b/googletest/test/googletest-json-output-unittest.py @@ -0,0 +1,618 @@ +#!/usr/bin/env python +# Copyright 2018, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Unit test for the gtest_json_output module.""" + +import datetime +import errno +import json +import os +import re +import sys + +import gtest_json_test_utils +import gtest_test_utils + +GTEST_FILTER_FLAG = '--gtest_filter' +GTEST_LIST_TESTS_FLAG = '--gtest_list_tests' +GTEST_OUTPUT_FLAG = '--gtest_output' +GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.json' +GTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_' + +# The flag indicating stacktraces are not supported +NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' + +SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv + +if SUPPORTS_STACK_TRACES: + STACK_TRACE_TEMPLATE = '\nStack trace:\n*' +else: + STACK_TRACE_TEMPLATE = '' + +EXPECTED_NON_EMPTY = { + u'tests': 23, + u'failures': 4, + u'disabled': 2, + u'errors': 0, + u'timestamp': u'*', + u'time': u'*', + u'ad_hoc_property': u'42', + u'name': u'AllTests', + u'testsuites': [ + { + u'name': u'SuccessfulTest', + u'tests': 1, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'testsuite': [ + { + u'name': u'Succeeds', + u'status': u'RUN', + u'time': u'*', + u'classname': u'SuccessfulTest' + } + ] + }, + { + u'name': u'FailedTest', + u'tests': 1, + u'failures': 1, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'testsuite': [ + { + u'name': u'Fails', + u'status': u'RUN', + u'time': u'*', + u'classname': u'FailedTest', + u'failures': [ + { + u'failure': + u'gtest_xml_output_unittest_.cc:*\n' + u'Expected equality of these values:\n' + u' 1\n 2' + STACK_TRACE_TEMPLATE, + u'type': u'' + } + ] + } + ] + }, + { + u'name': u'DisabledTest', + u'tests': 1, + u'failures': 0, + u'disabled': 1, + u'errors': 0, + u'time': u'*', + u'testsuite': [ + { + u'name': u'DISABLED_test_not_run', + u'status': u'NOTRUN', + u'time': u'*', + u'classname': u'DisabledTest' + } + ] + }, + { + u'name': u'MixedResultTest', + u'tests': 3, + u'failures': 1, + u'disabled': 1, + u'errors': 0, + u'time': u'*', + u'testsuite': [ + { + u'name': u'Succeeds', + u'status': u'RUN', + u'time': u'*', + u'classname': u'MixedResultTest' + }, + { + u'name': u'Fails', + u'status': u'RUN', + u'time': u'*', + u'classname': u'MixedResultTest', + u'failures': [ + { + u'failure': + u'gtest_xml_output_unittest_.cc:*\n' + u'Expected equality of these values:\n' + u' 1\n 2' + STACK_TRACE_TEMPLATE, + u'type': u'' + }, + { + u'failure': + u'gtest_xml_output_unittest_.cc:*\n' + u'Expected equality of these values:\n' + u' 2\n 3' + STACK_TRACE_TEMPLATE, + u'type': u'' + } + ] + }, + { + u'name': u'DISABLED_test', + u'status': u'NOTRUN', + u'time': u'*', + u'classname': u'MixedResultTest' + } + ] + }, + { + u'name': u'XmlQuotingTest', + u'tests': 1, + u'failures': 1, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'testsuite': [ + { + u'name': u'OutputsCData', + u'status': u'RUN', + u'time': u'*', + u'classname': u'XmlQuotingTest', + u'failures': [ + { + u'failure': + u'gtest_xml_output_unittest_.cc:*\n' + u'Failed\nXML output: ' + u'' + + STACK_TRACE_TEMPLATE, + u'type': u'' + } + ] + } + ] + }, + { + u'name': u'InvalidCharactersTest', + u'tests': 1, + u'failures': 1, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'testsuite': [ + { + u'name': u'InvalidCharactersInMessage', + u'status': u'RUN', + u'time': u'*', + u'classname': u'InvalidCharactersTest', + u'failures': [ + { + u'failure': + u'gtest_xml_output_unittest_.cc:*\n' + u'Failed\nInvalid characters in brackets' + u' [\x01\x02]' + STACK_TRACE_TEMPLATE, + u'type': u'' + } + ] + } + ] + }, + { + u'name': u'PropertyRecordingTest', + u'tests': 4, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'SetUpTestCase': u'yes', + u'TearDownTestCase': u'aye', + u'testsuite': [ + { + u'name': u'OneProperty', + u'status': u'RUN', + u'time': u'*', + u'classname': u'PropertyRecordingTest', + u'key_1': u'1' + }, + { + u'name': u'IntValuedProperty', + u'status': u'RUN', + u'time': u'*', + u'classname': u'PropertyRecordingTest', + u'key_int': u'1' + }, + { + u'name': u'ThreeProperties', + u'status': u'RUN', + u'time': u'*', + u'classname': u'PropertyRecordingTest', + u'key_1': u'1', + u'key_2': u'2', + u'key_3': u'3' + }, + { + u'name': u'TwoValuesForOneKeyUsesLastValue', + u'status': u'RUN', + u'time': u'*', + u'classname': u'PropertyRecordingTest', + u'key_1': u'2' + } + ] + }, + { + u'name': u'NoFixtureTest', + u'tests': 3, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'testsuite': [ + { + u'name': u'RecordProperty', + u'status': u'RUN', + u'time': u'*', + u'classname': u'NoFixtureTest', + u'key': u'1' + }, + { + u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty', + u'status': u'RUN', + u'time': u'*', + u'classname': u'NoFixtureTest', + u'key_for_utility_int': u'1' + }, + { + u'name': + u'ExternalUtilityThatCallsRecordStringValuedProperty', + u'status': u'RUN', + u'time': u'*', + u'classname': u'NoFixtureTest', + u'key_for_utility_string': u'1' + } + ] + }, + { + u'name': u'TypedTest/0', + u'tests': 1, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'testsuite': [ + { + u'name': u'HasTypeParamAttribute', + u'type_param': u'int', + u'status': u'RUN', + u'time': u'*', + u'classname': u'TypedTest/0' + } + ] + }, + { + u'name': u'TypedTest/1', + u'tests': 1, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'testsuite': [ + { + u'name': u'HasTypeParamAttribute', + u'type_param': u'long', + u'status': u'RUN', + u'time': u'*', + u'classname': u'TypedTest/1' + } + ] + }, + { + u'name': u'Single/TypeParameterizedTestCase/0', + u'tests': 1, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'testsuite': [ + { + u'name': u'HasTypeParamAttribute', + u'type_param': u'int', + u'status': u'RUN', + u'time': u'*', + u'classname': u'Single/TypeParameterizedTestCase/0' + } + ] + }, + { + u'name': u'Single/TypeParameterizedTestCase/1', + u'tests': 1, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'testsuite': [ + { + u'name': u'HasTypeParamAttribute', + u'type_param': u'long', + u'status': u'RUN', + u'time': u'*', + u'classname': u'Single/TypeParameterizedTestCase/1' + } + ] + }, + { + u'name': u'Single/ValueParamTest', + u'tests': 4, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'testsuite': [ + { + u'name': u'HasValueParamAttribute/0', + u'value_param': u'33', + u'status': u'RUN', + u'time': u'*', + u'classname': u'Single/ValueParamTest' + }, + { + u'name': u'HasValueParamAttribute/1', + u'value_param': u'42', + u'status': u'RUN', + u'time': u'*', + u'classname': u'Single/ValueParamTest' + }, + { + u'name': u'AnotherTestThatHasValueParamAttribute/0', + u'value_param': u'33', + u'status': u'RUN', + u'time': u'*', + u'classname': u'Single/ValueParamTest' + }, + { + u'name': u'AnotherTestThatHasValueParamAttribute/1', + u'value_param': u'42', + u'status': u'RUN', + u'time': u'*', + u'classname': u'Single/ValueParamTest' + } + ] + } + ] +} + +EXPECTED_FILTERED = { + u'tests': 1, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'timestamp': u'*', + u'name': u'AllTests', + u'ad_hoc_property': u'42', + u'testsuites': [{ + u'name': u'SuccessfulTest', + u'tests': 1, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'testsuite': [{ + u'name': u'Succeeds', + u'status': u'RUN', + u'time': u'*', + u'classname': u'SuccessfulTest', + }] + }], +} + +EXPECTED_EMPTY = { + u'tests': 0, + u'failures': 0, + u'disabled': 0, + u'errors': 0, + u'time': u'*', + u'timestamp': u'*', + u'name': u'AllTests', + u'testsuites': [], +} + +GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME) + +SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess( + [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output + + +class GTestJsonOutputUnitTest(gtest_test_utils.TestCase): + """Unit test for Google Test's JSON output functionality. + """ + + # This test currently breaks on platforms that do not support typed and + # type-parameterized tests, so we don't run it under them. + if SUPPORTS_TYPED_TESTS: + + def testNonEmptyJsonOutput(self): + """Verifies JSON output for a Google Test binary with non-empty output. + + Runs a test program that generates a non-empty JSON output, and + tests that the JSON output is expected. + """ + self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY, 1) + + def testEmptyJsonOutput(self): + """Verifies JSON output for a Google Test binary without actual tests. + + Runs a test program that generates an empty JSON output, and + tests that the JSON output is expected. + """ + + self._TestJsonOutput('gtest_no_test_unittest', EXPECTED_EMPTY, 0) + + def testTimestampValue(self): + """Checks whether the timestamp attribute in the JSON output is valid. + + Runs a test program that generates an empty JSON output, and checks if + the timestamp attribute in the testsuites tag is valid. + """ + actual = self._GetJsonOutput('gtest_no_test_unittest', [], 0) + date_time_str = actual['timestamp'] + # datetime.strptime() is only available in Python 2.5+ so we have to + # parse the expected datetime manually. + match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str) + self.assertTrue( + re.match, + 'JSON datettime string %s has incorrect format' % date_time_str) + date_time_from_json = datetime.datetime( + year=int(match.group(1)), month=int(match.group(2)), + day=int(match.group(3)), hour=int(match.group(4)), + minute=int(match.group(5)), second=int(match.group(6))) + + time_delta = abs(datetime.datetime.now() - date_time_from_json) + # timestamp value should be near the current local time + self.assertTrue(time_delta < datetime.timedelta(seconds=600), + 'time_delta is %s' % time_delta) + + def testDefaultOutputFile(self): + """Verifies the default output file name. + + Confirms that Google Test produces an JSON output file with the expected + default name if no name is explicitly specified. + """ + output_file = os.path.join(gtest_test_utils.GetTempDir(), + GTEST_DEFAULT_OUTPUT_FILE) + gtest_prog_path = gtest_test_utils.GetTestExecutablePath( + 'gtest_no_test_unittest') + try: + os.remove(output_file) + except OSError: + e = sys.exc_info()[1] + if e.errno != errno.ENOENT: + raise + + p = gtest_test_utils.Subprocess( + [gtest_prog_path, '%s=json' % GTEST_OUTPUT_FLAG], + working_dir=gtest_test_utils.GetTempDir()) + self.assert_(p.exited) + self.assertEquals(0, p.exit_code) + self.assert_(os.path.isfile(output_file)) + + def testSuppressedJsonOutput(self): + """Verifies that no JSON output is generated. + + Tests that no JSON file is generated if the default JSON listener is + shut down before RUN_ALL_TESTS is invoked. + """ + + json_path = os.path.join(gtest_test_utils.GetTempDir(), + GTEST_PROGRAM_NAME + 'out.json') + if os.path.isfile(json_path): + os.remove(json_path) + + command = [GTEST_PROGRAM_PATH, + '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path), + '--shut_down_xml'] + p = gtest_test_utils.Subprocess(command) + if p.terminated_by_signal: + # p.signal is available only if p.terminated_by_signal is True. + self.assertFalse( + p.terminated_by_signal, + '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal)) + else: + self.assert_(p.exited) + self.assertEquals(1, p.exit_code, + "'%s' exited with code %s, which doesn't match " + 'the expected exit code %s.' + % (command, p.exit_code, 1)) + + self.assert_(not os.path.isfile(json_path)) + + def testFilteredTestJsonOutput(self): + """Verifies JSON output when a filter is applied. + + Runs a test program that executes only some tests and verifies that + non-selected tests do not show up in the JSON output. + """ + + self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED, 0, + extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG]) + + def _GetJsonOutput(self, gtest_prog_name, extra_args, expected_exit_code): + """Returns the JSON output generated by running the program gtest_prog_name. + + Furthermore, the program's exit code must be expected_exit_code. + + Args: + gtest_prog_name: Google Test binary name. + extra_args: extra arguments to binary invocation. + expected_exit_code: program's exit code. + """ + json_path = os.path.join(gtest_test_utils.GetTempDir(), + gtest_prog_name + 'out.json') + gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name) + + command = ( + [gtest_prog_path, '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path)] + + extra_args + ) + p = gtest_test_utils.Subprocess(command) + if p.terminated_by_signal: + self.assert_(False, + '%s was killed by signal %d' % (gtest_prog_name, p.signal)) + else: + self.assert_(p.exited) + self.assertEquals(expected_exit_code, p.exit_code, + "'%s' exited with code %s, which doesn't match " + 'the expected exit code %s.' + % (command, p.exit_code, expected_exit_code)) + with open(json_path) as f: + actual = json.load(f) + return actual + + def _TestJsonOutput(self, gtest_prog_name, expected, + expected_exit_code, extra_args=None): + """Checks the JSON output generated by the Google Test binary. + + Asserts that the JSON document generated by running the program + gtest_prog_name matches expected_json, a string containing another + JSON document. Furthermore, the program's exit code must be + expected_exit_code. + + Args: + gtest_prog_name: Google Test binary name. + expected: expected output. + expected_exit_code: program's exit code. + extra_args: extra arguments to binary invocation. + """ + + actual = self._GetJsonOutput(gtest_prog_name, extra_args or [], + expected_exit_code) + self.assertEqual(expected, gtest_json_test_utils.normalize(actual)) + + +if __name__ == '__main__': + if NO_STACKTRACE_SUPPORT_FLAG in sys.argv: + # unittest.main() can't handle unknown flags + sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG) + + os.environ['GTEST_STACK_TRACE_DEPTH'] = '1' + gtest_test_utils.Main() -- cgit v0.12 From 421f527df32ff3f437166513d3621fd543bf42a7 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 16:23:20 -0400 Subject: more test changes --- googletest/test/BUILD.bazel | 6 +- googletest/test/googletest-message-test.cc | 159 +++ googletest/test/googletest-options-test.cc | 213 ++++ googletest/test/googletest-port-test.cc | 1303 ++++++++++++++++++++ googletest/test/googletest-printers-test.cc | 1737 +++++++++++++++++++++++++++ googletest/test/googletest-tuple-test.cc | 320 +++++ googletest/test/gtest-message_test.cc | 159 --- googletest/test/gtest-options_test.cc | 213 ---- googletest/test/gtest-port_test.cc | 1303 -------------------- googletest/test/gtest-printers_test.cc | 1737 --------------------------- googletest/test/gtest-tuple_test.cc | 320 ----- 11 files changed, 3735 insertions(+), 3735 deletions(-) create mode 100644 googletest/test/googletest-message-test.cc create mode 100644 googletest/test/googletest-options-test.cc create mode 100644 googletest/test/googletest-port-test.cc create mode 100644 googletest/test/googletest-printers-test.cc create mode 100644 googletest/test/googletest-tuple-test.cc delete mode 100644 googletest/test/gtest-message_test.cc delete mode 100644 googletest/test/gtest-options_test.cc delete mode 100644 googletest/test/gtest-port_test.cc delete mode 100644 googletest/test/gtest-printers_test.cc delete mode 100644 googletest/test/gtest-tuple_test.cc diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 7d0932b..a5c6b14 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -49,7 +49,7 @@ config_setting( values = {"define": "absl=1"}, ) -#on windows exclude gtest-tuple.h and gtest-tuple_test.cc +#on windows exclude gtest-tuple.h and googletest-tuple-test.cc cc_test( name = "gtest_all_test", size = "small", @@ -62,7 +62,7 @@ cc_test( ], exclude = [ "gtest-unittest-api_test.cc", - "gtest-tuple_test.cc", + "googletest-tuple-test.cc", "googletest/src/gtest-all.cc", "gtest_all_test.cc", "gtest-death-test_ex_test.cc", @@ -85,7 +85,7 @@ cc_test( "//:windows": [], "//:windows_msvc": [], "//conditions:default": [ - "gtest-tuple_test.cc", + "googletest-tuple-test.cc", ], }), copts = select({ diff --git a/googletest/test/googletest-message-test.cc b/googletest/test/googletest-message-test.cc new file mode 100644 index 0000000..175238e --- /dev/null +++ b/googletest/test/googletest-message-test.cc @@ -0,0 +1,159 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// Tests for the Message class. + +#include "gtest/gtest-message.h" + +#include "gtest/gtest.h" + +namespace { + +using ::testing::Message; + +// Tests the testing::Message class + +// Tests the default constructor. +TEST(MessageTest, DefaultConstructor) { + const Message msg; + EXPECT_EQ("", msg.GetString()); +} + +// Tests the copy constructor. +TEST(MessageTest, CopyConstructor) { + const Message msg1("Hello"); + const Message msg2(msg1); + EXPECT_EQ("Hello", msg2.GetString()); +} + +// Tests constructing a Message from a C-string. +TEST(MessageTest, ConstructsFromCString) { + Message msg("Hello"); + EXPECT_EQ("Hello", msg.GetString()); +} + +// Tests streaming a float. +TEST(MessageTest, StreamsFloat) { + const std::string s = (Message() << 1.23456F << " " << 2.34567F).GetString(); + // Both numbers should be printed with enough precision. + EXPECT_PRED_FORMAT2(testing::IsSubstring, "1.234560", s.c_str()); + EXPECT_PRED_FORMAT2(testing::IsSubstring, " 2.345669", s.c_str()); +} + +// Tests streaming a double. +TEST(MessageTest, StreamsDouble) { + const std::string s = (Message() << 1260570880.4555497 << " " + << 1260572265.1954534).GetString(); + // Both numbers should be printed with enough precision. + EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str()); + EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str()); +} + +// Tests streaming a non-char pointer. +TEST(MessageTest, StreamsPointer) { + int n = 0; + int* p = &n; + EXPECT_NE("(null)", (Message() << p).GetString()); +} + +// Tests streaming a NULL non-char pointer. +TEST(MessageTest, StreamsNullPointer) { + int* p = NULL; + EXPECT_EQ("(null)", (Message() << p).GetString()); +} + +// Tests streaming a C string. +TEST(MessageTest, StreamsCString) { + EXPECT_EQ("Foo", (Message() << "Foo").GetString()); +} + +// Tests streaming a NULL C string. +TEST(MessageTest, StreamsNullCString) { + char* p = NULL; + EXPECT_EQ("(null)", (Message() << p).GetString()); +} + +// Tests streaming std::string. +TEST(MessageTest, StreamsString) { + const ::std::string str("Hello"); + EXPECT_EQ("Hello", (Message() << str).GetString()); +} + +// Tests that we can output strings containing embedded NULs. +TEST(MessageTest, StreamsStringWithEmbeddedNUL) { + const char char_array_with_nul[] = + "Here's a NUL\0 and some more string"; + const ::std::string string_with_nul(char_array_with_nul, + sizeof(char_array_with_nul) - 1); + EXPECT_EQ("Here's a NUL\\0 and some more string", + (Message() << string_with_nul).GetString()); +} + +// Tests streaming a NUL char. +TEST(MessageTest, StreamsNULChar) { + EXPECT_EQ("\\0", (Message() << '\0').GetString()); +} + +// Tests streaming int. +TEST(MessageTest, StreamsInt) { + EXPECT_EQ("123", (Message() << 123).GetString()); +} + +// Tests that basic IO manipulators (endl, ends, and flush) can be +// streamed to Message. +TEST(MessageTest, StreamsBasicIoManip) { + EXPECT_EQ("Line 1.\nA NUL char \\0 in line 2.", + (Message() << "Line 1." << std::endl + << "A NUL char " << std::ends << std::flush + << " in line 2.").GetString()); +} + +// Tests Message::GetString() +TEST(MessageTest, GetString) { + Message msg; + msg << 1 << " lamb"; + EXPECT_EQ("1 lamb", msg.GetString()); +} + +// Tests streaming a Message object to an ostream. +TEST(MessageTest, StreamsToOStream) { + Message msg("Hello"); + ::std::stringstream ss; + ss << msg; + EXPECT_EQ("Hello", testing::internal::StringStreamToString(&ss)); +} + +// Tests that a Message object doesn't take up too much stack space. +TEST(MessageTest, DoesNotTakeUpMuchStackSpace) { + EXPECT_LE(sizeof(Message), 16U); +} + +} // namespace diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc new file mode 100644 index 0000000..e4c0d04 --- /dev/null +++ b/googletest/test/googletest-options-test.cc @@ -0,0 +1,213 @@ +// 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. +// +// +// Google Test UnitTestOptions tests +// +// This file tests classes and functions used internally by +// Google Test. They are subject to change without notice. +// +// This file is #included from gtest.cc, to avoid changing build or +// make-files on Windows and other platforms. Do not #include this file +// anywhere else! + +#include "gtest/gtest.h" + +#if GTEST_OS_WINDOWS_MOBILE +# include +#elif GTEST_OS_WINDOWS +# include +#endif // GTEST_OS_WINDOWS_MOBILE + +#include "src/gtest-internal-inl.h" + +namespace testing { +namespace internal { +namespace { + +// Turns the given relative path into an absolute path. +FilePath GetAbsolutePathOf(const FilePath& relative_path) { + return FilePath::ConcatPaths(FilePath::GetCurrentDir(), relative_path); +} + +// Testing UnitTestOptions::GetOutputFormat/GetOutputFile. + +TEST(XmlOutputTest, GetOutputFormatDefault) { + GTEST_FLAG(output) = ""; + EXPECT_STREQ("", UnitTestOptions::GetOutputFormat().c_str()); +} + +TEST(XmlOutputTest, GetOutputFormat) { + GTEST_FLAG(output) = "xml:filename"; + EXPECT_STREQ("xml", UnitTestOptions::GetOutputFormat().c_str()); +} + +TEST(XmlOutputTest, GetOutputFileDefault) { + GTEST_FLAG(output) = ""; + EXPECT_EQ(GetAbsolutePathOf(FilePath("test_detail.xml")).string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +} + +TEST(XmlOutputTest, GetOutputFileSingleFile) { + GTEST_FLAG(output) = "xml:filename.abc"; + EXPECT_EQ(GetAbsolutePathOf(FilePath("filename.abc")).string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +} + +TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) { + GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_; + const std::string expected_output_file = + GetAbsolutePathOf( + FilePath(std::string("path") + GTEST_PATH_SEP_ + + GetCurrentExecutableName().string() + ".xml")).string(); + const std::string& output_file = + UnitTestOptions::GetAbsolutePathToOutputFile(); +#if GTEST_OS_WINDOWS + EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); +#else + EXPECT_EQ(expected_output_file, output_file.c_str()); +#endif +} + +TEST(OutputFileHelpersTest, GetCurrentExecutableName) { + const std::string exe_str = GetCurrentExecutableName().string(); +#if GTEST_OS_WINDOWS + const bool success = + _strcmpi("googletest-options-test", exe_str.c_str()) == 0 || + _strcmpi("gtest-options-ex_test", exe_str.c_str()) == 0 || + _strcmpi("gtest_all_test", exe_str.c_str()) == 0 || + _strcmpi("gtest_dll_test", exe_str.c_str()) == 0; +#elif GTEST_OS_FUCHSIA + const bool success = exe_str == "app"; +#else + // TODO(wan@google.com): remove the hard-coded "lt-" prefix when + // Chandler Carruth's libtool replacement is ready. + const bool success = + exe_str == "googletest-options-test" || + exe_str == "gtest_all_test" || + exe_str == "lt-gtest_all_test" || + exe_str == "gtest_dll_test"; +#endif // GTEST_OS_WINDOWS + if (!success) + FAIL() << "GetCurrentExecutableName() returns " << exe_str; +} + +#if !GTEST_OS_FUCHSIA + +class XmlOutputChangeDirTest : public Test { + protected: + virtual void SetUp() { + original_working_dir_ = FilePath::GetCurrentDir(); + posix::ChDir(".."); + // This will make the test fail if run from the root directory. + EXPECT_NE(original_working_dir_.string(), + FilePath::GetCurrentDir().string()); + } + + virtual void TearDown() { + posix::ChDir(original_working_dir_.string().c_str()); + } + + FilePath original_working_dir_; +}; + +TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) { + GTEST_FLAG(output) = ""; + EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, + FilePath("test_detail.xml")).string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +} + +TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) { + GTEST_FLAG(output) = "xml"; + EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, + FilePath("test_detail.xml")).string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +} + +TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) { + GTEST_FLAG(output) = "xml:filename.abc"; + EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, + FilePath("filename.abc")).string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +} + +TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { + GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_; + const std::string expected_output_file = + FilePath::ConcatPaths( + original_working_dir_, + FilePath(std::string("path") + GTEST_PATH_SEP_ + + GetCurrentExecutableName().string() + ".xml")).string(); + const std::string& output_file = + UnitTestOptions::GetAbsolutePathToOutputFile(); +#if GTEST_OS_WINDOWS + EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); +#else + EXPECT_EQ(expected_output_file, output_file.c_str()); +#endif +} + +TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) { +#if GTEST_OS_WINDOWS + GTEST_FLAG(output) = "xml:c:\\tmp\\filename.abc"; + EXPECT_EQ(FilePath("c:\\tmp\\filename.abc").string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +#else + GTEST_FLAG(output) ="xml:/tmp/filename.abc"; + EXPECT_EQ(FilePath("/tmp/filename.abc").string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +#endif +} + +TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) { +#if GTEST_OS_WINDOWS + const std::string path = "c:\\tmp\\"; +#else + const std::string path = "/tmp/"; +#endif + + GTEST_FLAG(output) = "xml:" + path; + const std::string expected_output_file = + path + GetCurrentExecutableName().string() + ".xml"; + const std::string& output_file = + UnitTestOptions::GetAbsolutePathToOutputFile(); + +#if GTEST_OS_WINDOWS + EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); +#else + EXPECT_EQ(expected_output_file, output_file.c_str()); +#endif +} + +#endif // !GTEST_OS_FUCHSIA + +} // namespace +} // namespace internal +} // namespace testing diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc new file mode 100644 index 0000000..15a629f --- /dev/null +++ b/googletest/test/googletest-port-test.cc @@ -0,0 +1,1303 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: vladl@google.com (Vlad Losev), wan@google.com (Zhanyong Wan) +// +// This file tests the internal cross-platform support utilities. + +#include "gtest/internal/gtest-port.h" + +#include + +#if GTEST_OS_MAC +# include +#endif // GTEST_OS_MAC + +#include +#include // For std::pair and std::make_pair. +#include + +#include "gtest/gtest.h" +#include "gtest/gtest-spi.h" +#include "src/gtest-internal-inl.h" + +using std::make_pair; +using std::pair; + +namespace testing { +namespace internal { + +TEST(IsXDigitTest, WorksForNarrowAscii) { + EXPECT_TRUE(IsXDigit('0')); + EXPECT_TRUE(IsXDigit('9')); + EXPECT_TRUE(IsXDigit('A')); + EXPECT_TRUE(IsXDigit('F')); + EXPECT_TRUE(IsXDigit('a')); + EXPECT_TRUE(IsXDigit('f')); + + EXPECT_FALSE(IsXDigit('-')); + EXPECT_FALSE(IsXDigit('g')); + EXPECT_FALSE(IsXDigit('G')); +} + +TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) { + EXPECT_FALSE(IsXDigit(static_cast('\x80'))); + EXPECT_FALSE(IsXDigit(static_cast('0' | '\x80'))); +} + +TEST(IsXDigitTest, WorksForWideAscii) { + EXPECT_TRUE(IsXDigit(L'0')); + EXPECT_TRUE(IsXDigit(L'9')); + EXPECT_TRUE(IsXDigit(L'A')); + EXPECT_TRUE(IsXDigit(L'F')); + EXPECT_TRUE(IsXDigit(L'a')); + EXPECT_TRUE(IsXDigit(L'f')); + + EXPECT_FALSE(IsXDigit(L'-')); + EXPECT_FALSE(IsXDigit(L'g')); + EXPECT_FALSE(IsXDigit(L'G')); +} + +TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) { + EXPECT_FALSE(IsXDigit(static_cast(0x80))); + EXPECT_FALSE(IsXDigit(static_cast(L'0' | 0x80))); + EXPECT_FALSE(IsXDigit(static_cast(L'0' | 0x100))); +} + +class Base { + public: + // Copy constructor and assignment operator do exactly what we need, so we + // use them. + Base() : member_(0) {} + explicit Base(int n) : member_(n) {} + virtual ~Base() {} + int member() { return member_; } + + private: + int member_; +}; + +class Derived : public Base { + public: + explicit Derived(int n) : Base(n) {} +}; + +TEST(ImplicitCastTest, ConvertsPointers) { + Derived derived(0); + EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_(&derived)); +} + +TEST(ImplicitCastTest, CanUseInheritance) { + Derived derived(1); + Base base = ::testing::internal::ImplicitCast_(derived); + EXPECT_EQ(derived.member(), base.member()); +} + +class Castable { + public: + explicit Castable(bool* converted) : converted_(converted) {} + operator Base() { + *converted_ = true; + return Base(); + } + + private: + bool* converted_; +}; + +TEST(ImplicitCastTest, CanUseNonConstCastOperator) { + bool converted = false; + Castable castable(&converted); + Base base = ::testing::internal::ImplicitCast_(castable); + EXPECT_TRUE(converted); +} + +class ConstCastable { + public: + explicit ConstCastable(bool* converted) : converted_(converted) {} + operator Base() const { + *converted_ = true; + return Base(); + } + + private: + bool* converted_; +}; + +TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) { + bool converted = false; + const ConstCastable const_castable(&converted); + Base base = ::testing::internal::ImplicitCast_(const_castable); + EXPECT_TRUE(converted); +} + +class ConstAndNonConstCastable { + public: + ConstAndNonConstCastable(bool* converted, bool* const_converted) + : converted_(converted), const_converted_(const_converted) {} + operator Base() { + *converted_ = true; + return Base(); + } + operator Base() const { + *const_converted_ = true; + return Base(); + } + + private: + bool* converted_; + bool* const_converted_; +}; + +TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) { + bool converted = false; + bool const_converted = false; + ConstAndNonConstCastable castable(&converted, &const_converted); + Base base = ::testing::internal::ImplicitCast_(castable); + EXPECT_TRUE(converted); + EXPECT_FALSE(const_converted); + + converted = false; + const_converted = false; + const ConstAndNonConstCastable const_castable(&converted, &const_converted); + base = ::testing::internal::ImplicitCast_(const_castable); + EXPECT_FALSE(converted); + EXPECT_TRUE(const_converted); +} + +class To { + public: + To(bool* converted) { *converted = true; } // NOLINT +}; + +TEST(ImplicitCastTest, CanUseImplicitConstructor) { + bool converted = false; + To to = ::testing::internal::ImplicitCast_(&converted); + (void)to; + EXPECT_TRUE(converted); +} + +TEST(IteratorTraitsTest, WorksForSTLContainerIterators) { + StaticAssertTypeEq::const_iterator>::value_type>(); + StaticAssertTypeEq::iterator>::value_type>(); +} + +TEST(IteratorTraitsTest, WorksForPointerToNonConst) { + StaticAssertTypeEq::value_type>(); + StaticAssertTypeEq::value_type>(); +} + +TEST(IteratorTraitsTest, WorksForPointerToConst) { + StaticAssertTypeEq::value_type>(); + StaticAssertTypeEq::value_type>(); +} + +// Tests that the element_type typedef is available in scoped_ptr and refers +// to the parameter type. +TEST(ScopedPtrTest, DefinesElementType) { + StaticAssertTypeEq::element_type>(); +} + +// TODO(vladl@google.com): Implement THE REST of scoped_ptr tests. + +TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) { + if (AlwaysFalse()) + GTEST_CHECK_(false) << "This should never be executed; " + "It's a compilation test only."; + + if (AlwaysTrue()) + GTEST_CHECK_(true); + else + ; // NOLINT + + if (AlwaysFalse()) + ; // NOLINT + else + GTEST_CHECK_(true) << ""; +} + +TEST(GtestCheckSyntaxTest, WorksWithSwitch) { + switch (0) { + case 1: + break; + default: + GTEST_CHECK_(true); + } + + switch (0) + case 0: + GTEST_CHECK_(true) << "Check failed in switch case"; +} + +// Verifies behavior of FormatFileLocation. +TEST(FormatFileLocationTest, FormatsFileLocation) { + EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42)); + EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42)); +} + +TEST(FormatFileLocationTest, FormatsUnknownFile) { + EXPECT_PRED_FORMAT2( + IsSubstring, "unknown file", FormatFileLocation(NULL, 42)); + EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(NULL, 42)); +} + +TEST(FormatFileLocationTest, FormatsUknownLine) { + EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1)); +} + +TEST(FormatFileLocationTest, FormatsUknownFileAndLine) { + EXPECT_EQ("unknown file:", FormatFileLocation(NULL, -1)); +} + +// Verifies behavior of FormatCompilerIndependentFileLocation. +TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) { + EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42)); +} + +TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) { + EXPECT_EQ("unknown file:42", + FormatCompilerIndependentFileLocation(NULL, 42)); +} + +TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) { + EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1)); +} + +TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) { + EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1)); +} + +#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA +void* ThreadFunc(void* data) { + internal::Mutex* mutex = static_cast(data); + mutex->Lock(); + mutex->Unlock(); + return NULL; +} + +TEST(GetThreadCountTest, ReturnsCorrectValue) { + const size_t starting_count = GetThreadCount(); + pthread_t thread_id; + + internal::Mutex mutex; + { + internal::MutexLock lock(&mutex); + pthread_attr_t attr; + ASSERT_EQ(0, pthread_attr_init(&attr)); + ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); + + const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex); + ASSERT_EQ(0, pthread_attr_destroy(&attr)); + ASSERT_EQ(0, status); + EXPECT_EQ(starting_count + 1, GetThreadCount()); + } + + void* dummy; + ASSERT_EQ(0, pthread_join(thread_id, &dummy)); + + // The OS may not immediately report the updated thread count after + // joining a thread, causing flakiness in this test. To counter that, we + // wait for up to .5 seconds for the OS to report the correct value. + for (int i = 0; i < 5; ++i) { + if (GetThreadCount() == starting_count) + break; + + SleepMilliseconds(100); + } + + EXPECT_EQ(starting_count, GetThreadCount()); +} +#else +TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) { + EXPECT_EQ(0U, GetThreadCount()); +} +#endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA + +TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { + const bool a_false_condition = false; + const char regex[] = +#ifdef _MSC_VER + "googletest-port-test\\.cc\\(\\d+\\):" +#elif GTEST_USES_POSIX_RE + "googletest-port-test\\.cc:[0-9]+" +#else + "googletest-port-test\\.cc:\\d+" +#endif // _MSC_VER + ".*a_false_condition.*Extra info.*"; + + EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info", + regex); +} + +#if GTEST_HAS_DEATH_TEST + +TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { + EXPECT_EXIT({ + GTEST_CHECK_(true) << "Extra info"; + ::std::cerr << "Success\n"; + exit(0); }, + ::testing::ExitedWithCode(0), "Success"); +} + +#endif // GTEST_HAS_DEATH_TEST + +// Verifies that Google Test choose regular expression engine appropriate to +// the platform. The test will produce compiler errors in case of failure. +// For simplicity, we only cover the most important platforms here. +TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) { +#if !GTEST_USES_PCRE +# if GTEST_HAS_POSIX_RE + + EXPECT_TRUE(GTEST_USES_POSIX_RE); + +# else + + EXPECT_TRUE(GTEST_USES_SIMPLE_RE); + +# endif +#endif // !GTEST_USES_PCRE +} + +#if GTEST_USES_POSIX_RE + +# if GTEST_HAS_TYPED_TEST + +template +class RETest : public ::testing::Test {}; + +// Defines StringTypes as the list of all string types that class RE +// supports. +typedef testing::Types< + ::std::string, +# if GTEST_HAS_GLOBAL_STRING + ::string, +# endif // GTEST_HAS_GLOBAL_STRING + const char*> StringTypes; + +TYPED_TEST_CASE(RETest, StringTypes); + +// Tests RE's implicit constructors. +TYPED_TEST(RETest, ImplicitConstructorWorks) { + const RE empty(TypeParam("")); + EXPECT_STREQ("", empty.pattern()); + + const RE simple(TypeParam("hello")); + EXPECT_STREQ("hello", simple.pattern()); + + const RE normal(TypeParam(".*(\\w+)")); + EXPECT_STREQ(".*(\\w+)", normal.pattern()); +} + +// Tests that RE's constructors reject invalid regular expressions. +TYPED_TEST(RETest, RejectsInvalidRegex) { + EXPECT_NONFATAL_FAILURE({ + const RE invalid(TypeParam("?")); + }, "\"?\" is not a valid POSIX Extended regular expression."); +} + +// Tests RE::FullMatch(). +TYPED_TEST(RETest, FullMatchWorks) { + const RE empty(TypeParam("")); + EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty)); + EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty)); + + const RE re(TypeParam("a.*z")); + EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re)); + EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re)); + EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re)); + EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re)); +} + +// Tests RE::PartialMatch(). +TYPED_TEST(RETest, PartialMatchWorks) { + const RE empty(TypeParam("")); + EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty)); + EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty)); + + const RE re(TypeParam("a.*z")); + EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re)); + EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re)); + EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re)); + EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re)); + EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re)); +} + +# endif // GTEST_HAS_TYPED_TEST + +#elif GTEST_USES_SIMPLE_RE + +TEST(IsInSetTest, NulCharIsNotInAnySet) { + EXPECT_FALSE(IsInSet('\0', "")); + EXPECT_FALSE(IsInSet('\0', "\0")); + EXPECT_FALSE(IsInSet('\0', "a")); +} + +TEST(IsInSetTest, WorksForNonNulChars) { + EXPECT_FALSE(IsInSet('a', "Ab")); + EXPECT_FALSE(IsInSet('c', "")); + + EXPECT_TRUE(IsInSet('b', "bcd")); + EXPECT_TRUE(IsInSet('b', "ab")); +} + +TEST(IsAsciiDigitTest, IsFalseForNonDigit) { + EXPECT_FALSE(IsAsciiDigit('\0')); + EXPECT_FALSE(IsAsciiDigit(' ')); + EXPECT_FALSE(IsAsciiDigit('+')); + EXPECT_FALSE(IsAsciiDigit('-')); + EXPECT_FALSE(IsAsciiDigit('.')); + EXPECT_FALSE(IsAsciiDigit('a')); +} + +TEST(IsAsciiDigitTest, IsTrueForDigit) { + EXPECT_TRUE(IsAsciiDigit('0')); + EXPECT_TRUE(IsAsciiDigit('1')); + EXPECT_TRUE(IsAsciiDigit('5')); + EXPECT_TRUE(IsAsciiDigit('9')); +} + +TEST(IsAsciiPunctTest, IsFalseForNonPunct) { + EXPECT_FALSE(IsAsciiPunct('\0')); + EXPECT_FALSE(IsAsciiPunct(' ')); + EXPECT_FALSE(IsAsciiPunct('\n')); + EXPECT_FALSE(IsAsciiPunct('a')); + EXPECT_FALSE(IsAsciiPunct('0')); +} + +TEST(IsAsciiPunctTest, IsTrueForPunct) { + for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) { + EXPECT_PRED1(IsAsciiPunct, *p); + } +} + +TEST(IsRepeatTest, IsFalseForNonRepeatChar) { + EXPECT_FALSE(IsRepeat('\0')); + EXPECT_FALSE(IsRepeat(' ')); + EXPECT_FALSE(IsRepeat('a')); + EXPECT_FALSE(IsRepeat('1')); + EXPECT_FALSE(IsRepeat('-')); +} + +TEST(IsRepeatTest, IsTrueForRepeatChar) { + EXPECT_TRUE(IsRepeat('?')); + EXPECT_TRUE(IsRepeat('*')); + EXPECT_TRUE(IsRepeat('+')); +} + +TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) { + EXPECT_FALSE(IsAsciiWhiteSpace('\0')); + EXPECT_FALSE(IsAsciiWhiteSpace('a')); + EXPECT_FALSE(IsAsciiWhiteSpace('1')); + EXPECT_FALSE(IsAsciiWhiteSpace('+')); + EXPECT_FALSE(IsAsciiWhiteSpace('_')); +} + +TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) { + EXPECT_TRUE(IsAsciiWhiteSpace(' ')); + EXPECT_TRUE(IsAsciiWhiteSpace('\n')); + EXPECT_TRUE(IsAsciiWhiteSpace('\r')); + EXPECT_TRUE(IsAsciiWhiteSpace('\t')); + EXPECT_TRUE(IsAsciiWhiteSpace('\v')); + EXPECT_TRUE(IsAsciiWhiteSpace('\f')); +} + +TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) { + EXPECT_FALSE(IsAsciiWordChar('\0')); + EXPECT_FALSE(IsAsciiWordChar('+')); + EXPECT_FALSE(IsAsciiWordChar('.')); + EXPECT_FALSE(IsAsciiWordChar(' ')); + EXPECT_FALSE(IsAsciiWordChar('\n')); +} + +TEST(IsAsciiWordCharTest, IsTrueForLetter) { + EXPECT_TRUE(IsAsciiWordChar('a')); + EXPECT_TRUE(IsAsciiWordChar('b')); + EXPECT_TRUE(IsAsciiWordChar('A')); + EXPECT_TRUE(IsAsciiWordChar('Z')); +} + +TEST(IsAsciiWordCharTest, IsTrueForDigit) { + EXPECT_TRUE(IsAsciiWordChar('0')); + EXPECT_TRUE(IsAsciiWordChar('1')); + EXPECT_TRUE(IsAsciiWordChar('7')); + EXPECT_TRUE(IsAsciiWordChar('9')); +} + +TEST(IsAsciiWordCharTest, IsTrueForUnderscore) { + EXPECT_TRUE(IsAsciiWordChar('_')); +} + +TEST(IsValidEscapeTest, IsFalseForNonPrintable) { + EXPECT_FALSE(IsValidEscape('\0')); + EXPECT_FALSE(IsValidEscape('\007')); +} + +TEST(IsValidEscapeTest, IsFalseForDigit) { + EXPECT_FALSE(IsValidEscape('0')); + EXPECT_FALSE(IsValidEscape('9')); +} + +TEST(IsValidEscapeTest, IsFalseForWhiteSpace) { + EXPECT_FALSE(IsValidEscape(' ')); + EXPECT_FALSE(IsValidEscape('\n')); +} + +TEST(IsValidEscapeTest, IsFalseForSomeLetter) { + EXPECT_FALSE(IsValidEscape('a')); + EXPECT_FALSE(IsValidEscape('Z')); +} + +TEST(IsValidEscapeTest, IsTrueForPunct) { + EXPECT_TRUE(IsValidEscape('.')); + EXPECT_TRUE(IsValidEscape('-')); + EXPECT_TRUE(IsValidEscape('^')); + EXPECT_TRUE(IsValidEscape('$')); + EXPECT_TRUE(IsValidEscape('(')); + EXPECT_TRUE(IsValidEscape(']')); + EXPECT_TRUE(IsValidEscape('{')); + EXPECT_TRUE(IsValidEscape('|')); +} + +TEST(IsValidEscapeTest, IsTrueForSomeLetter) { + EXPECT_TRUE(IsValidEscape('d')); + EXPECT_TRUE(IsValidEscape('D')); + EXPECT_TRUE(IsValidEscape('s')); + EXPECT_TRUE(IsValidEscape('S')); + EXPECT_TRUE(IsValidEscape('w')); + EXPECT_TRUE(IsValidEscape('W')); +} + +TEST(AtomMatchesCharTest, EscapedPunct) { + EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, '\\', ' ')); + EXPECT_FALSE(AtomMatchesChar(true, '_', '.')); + EXPECT_FALSE(AtomMatchesChar(true, '.', 'a')); + + EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\')); + EXPECT_TRUE(AtomMatchesChar(true, '_', '_')); + EXPECT_TRUE(AtomMatchesChar(true, '+', '+')); + EXPECT_TRUE(AtomMatchesChar(true, '.', '.')); +} + +TEST(AtomMatchesCharTest, Escaped_d) { + EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a')); + EXPECT_FALSE(AtomMatchesChar(true, 'd', '.')); + + EXPECT_TRUE(AtomMatchesChar(true, 'd', '0')); + EXPECT_TRUE(AtomMatchesChar(true, 'd', '9')); +} + +TEST(AtomMatchesCharTest, Escaped_D) { + EXPECT_FALSE(AtomMatchesChar(true, 'D', '0')); + EXPECT_FALSE(AtomMatchesChar(true, 'D', '9')); + + EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0')); + EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a')); + EXPECT_TRUE(AtomMatchesChar(true, 'D', '-')); +} + +TEST(AtomMatchesCharTest, Escaped_s) { + EXPECT_FALSE(AtomMatchesChar(true, 's', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 's', 'a')); + EXPECT_FALSE(AtomMatchesChar(true, 's', '.')); + EXPECT_FALSE(AtomMatchesChar(true, 's', '9')); + + EXPECT_TRUE(AtomMatchesChar(true, 's', ' ')); + EXPECT_TRUE(AtomMatchesChar(true, 's', '\n')); + EXPECT_TRUE(AtomMatchesChar(true, 's', '\t')); +} + +TEST(AtomMatchesCharTest, Escaped_S) { + EXPECT_FALSE(AtomMatchesChar(true, 'S', ' ')); + EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r')); + + EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0')); + EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a')); + EXPECT_TRUE(AtomMatchesChar(true, 'S', '9')); +} + +TEST(AtomMatchesCharTest, Escaped_w) { + EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 'w', '+')); + EXPECT_FALSE(AtomMatchesChar(true, 'w', ' ')); + EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n')); + + EXPECT_TRUE(AtomMatchesChar(true, 'w', '0')); + EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b')); + EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C')); + EXPECT_TRUE(AtomMatchesChar(true, 'w', '_')); +} + +TEST(AtomMatchesCharTest, Escaped_W) { + EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A')); + EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b')); + EXPECT_FALSE(AtomMatchesChar(true, 'W', '9')); + EXPECT_FALSE(AtomMatchesChar(true, 'W', '_')); + + EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0')); + EXPECT_TRUE(AtomMatchesChar(true, 'W', '*')); + EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n')); +} + +TEST(AtomMatchesCharTest, EscapedWhiteSpace) { + EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n')); + EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r')); + EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a')); + EXPECT_FALSE(AtomMatchesChar(true, 't', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 't', 't')); + EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f')); + + EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f')); + EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n')); + EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r')); + EXPECT_TRUE(AtomMatchesChar(true, 't', '\t')); + EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v')); +} + +TEST(AtomMatchesCharTest, UnescapedDot) { + EXPECT_FALSE(AtomMatchesChar(false, '.', '\n')); + + EXPECT_TRUE(AtomMatchesChar(false, '.', '\0')); + EXPECT_TRUE(AtomMatchesChar(false, '.', '.')); + EXPECT_TRUE(AtomMatchesChar(false, '.', 'a')); + EXPECT_TRUE(AtomMatchesChar(false, '.', ' ')); +} + +TEST(AtomMatchesCharTest, UnescapedChar) { + EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0')); + EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b')); + EXPECT_FALSE(AtomMatchesChar(false, '$', 'a')); + + EXPECT_TRUE(AtomMatchesChar(false, '$', '$')); + EXPECT_TRUE(AtomMatchesChar(false, '5', '5')); + EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z')); +} + +TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) { + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)), + "NULL is not a valid simple regular expression"); + EXPECT_NONFATAL_FAILURE( + ASSERT_FALSE(ValidateRegex("a\\")), + "Syntax error at index 1 in simple regular expression \"a\\\": "); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")), + "'\\' cannot appear at the end"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")), + "'\\' cannot appear at the end"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")), + "invalid escape sequence \"\\h\""); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")), + "'^' can only appear at the beginning"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")), + "'^' can only appear at the beginning"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")), + "'$' can only appear at the end"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")), + "'$' can only appear at the end"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")), + "'(' is unsupported"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")), + "')' is unsupported"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")), + "'[' is unsupported"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")), + "'{' is unsupported"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")), + "'?' can only follow a repeatable token"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")), + "'*' can only follow a repeatable token"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")), + "'+' can only follow a repeatable token"); +} + +TEST(ValidateRegexTest, ReturnsTrueForValid) { + EXPECT_TRUE(ValidateRegex("")); + EXPECT_TRUE(ValidateRegex("a")); + EXPECT_TRUE(ValidateRegex(".*")); + EXPECT_TRUE(ValidateRegex("^a_+")); + EXPECT_TRUE(ValidateRegex("^a\\t\\&?")); + EXPECT_TRUE(ValidateRegex("09*$")); + EXPECT_TRUE(ValidateRegex("^Z$")); + EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}")); +} + +TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) { + EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba")); + // Repeating more than once. + EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab")); + + // Repeating zero times. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba")); + // Repeating once. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab")); + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##")); +} + +TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) { + EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab")); + + // Repeating zero times. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc")); + // Repeating once. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc")); + // Repeating more than once. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g")); +} + +TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) { + EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab")); + // Repeating zero times. + EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc")); + + // Repeating once. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc")); + // Repeating more than once. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g")); +} + +TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) { + EXPECT_TRUE(MatchRegexAtHead("", "")); + EXPECT_TRUE(MatchRegexAtHead("", "ab")); +} + +TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) { + EXPECT_FALSE(MatchRegexAtHead("$", "a")); + + EXPECT_TRUE(MatchRegexAtHead("$", "")); + EXPECT_TRUE(MatchRegexAtHead("a$", "a")); +} + +TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) { + EXPECT_FALSE(MatchRegexAtHead("\\w", "+")); + EXPECT_FALSE(MatchRegexAtHead("\\W", "ab")); + + EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab")); + EXPECT_TRUE(MatchRegexAtHead("\\d", "1a")); +} + +TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) { + EXPECT_FALSE(MatchRegexAtHead(".+a", "abc")); + EXPECT_FALSE(MatchRegexAtHead("a?b", "aab")); + + EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab")); + EXPECT_TRUE(MatchRegexAtHead("a?b", "b")); + EXPECT_TRUE(MatchRegexAtHead("a?b", "ab")); +} + +TEST(MatchRegexAtHeadTest, + WorksWhenRegexStartsWithRepetionOfEscapeSequence) { + EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc")); + EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b")); + + EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab")); + EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b")); + EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b")); + EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b")); +} + +TEST(MatchRegexAtHeadTest, MatchesSequentially) { + EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc")); + + EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc")); +} + +TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) { + EXPECT_FALSE(MatchRegexAnywhere("", NULL)); +} + +TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) { + EXPECT_FALSE(MatchRegexAnywhere("^a", "ba")); + EXPECT_FALSE(MatchRegexAnywhere("^$", "a")); + + EXPECT_TRUE(MatchRegexAnywhere("^a", "ab")); + EXPECT_TRUE(MatchRegexAnywhere("^", "ab")); + EXPECT_TRUE(MatchRegexAnywhere("^$", "")); +} + +TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) { + EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123")); + EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888")); +} + +TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) { + EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5")); + EXPECT_TRUE(MatchRegexAnywhere(".*=", "=")); + EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc")); +} + +TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) { + EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5")); + EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...=")); +} + +// Tests RE's implicit constructors. +TEST(RETest, ImplicitConstructorWorks) { + const RE empty(""); + EXPECT_STREQ("", empty.pattern()); + + const RE simple("hello"); + EXPECT_STREQ("hello", simple.pattern()); +} + +// Tests that RE's constructors reject invalid regular expressions. +TEST(RETest, RejectsInvalidRegex) { + EXPECT_NONFATAL_FAILURE({ + const RE normal(NULL); + }, "NULL is not a valid simple regular expression"); + + EXPECT_NONFATAL_FAILURE({ + const RE normal(".*(\\w+"); + }, "'(' is unsupported"); + + EXPECT_NONFATAL_FAILURE({ + const RE invalid("^?"); + }, "'?' can only follow a repeatable token"); +} + +// Tests RE::FullMatch(). +TEST(RETest, FullMatchWorks) { + const RE empty(""); + EXPECT_TRUE(RE::FullMatch("", empty)); + EXPECT_FALSE(RE::FullMatch("a", empty)); + + const RE re1("a"); + EXPECT_TRUE(RE::FullMatch("a", re1)); + + const RE re("a.*z"); + EXPECT_TRUE(RE::FullMatch("az", re)); + EXPECT_TRUE(RE::FullMatch("axyz", re)); + EXPECT_FALSE(RE::FullMatch("baz", re)); + EXPECT_FALSE(RE::FullMatch("azy", re)); +} + +// Tests RE::PartialMatch(). +TEST(RETest, PartialMatchWorks) { + const RE empty(""); + EXPECT_TRUE(RE::PartialMatch("", empty)); + EXPECT_TRUE(RE::PartialMatch("a", empty)); + + const RE re("a.*z"); + EXPECT_TRUE(RE::PartialMatch("az", re)); + EXPECT_TRUE(RE::PartialMatch("axyz", re)); + EXPECT_TRUE(RE::PartialMatch("baz", re)); + EXPECT_TRUE(RE::PartialMatch("azy", re)); + EXPECT_FALSE(RE::PartialMatch("zza", re)); +} + +#endif // GTEST_USES_POSIX_RE + +#if !GTEST_OS_WINDOWS_MOBILE + +TEST(CaptureTest, CapturesStdout) { + CaptureStdout(); + fprintf(stdout, "abc"); + EXPECT_STREQ("abc", GetCapturedStdout().c_str()); + + CaptureStdout(); + fprintf(stdout, "def%cghi", '\0'); + EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout())); +} + +TEST(CaptureTest, CapturesStderr) { + CaptureStderr(); + fprintf(stderr, "jkl"); + EXPECT_STREQ("jkl", GetCapturedStderr().c_str()); + + CaptureStderr(); + fprintf(stderr, "jkl%cmno", '\0'); + EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr())); +} + +// Tests that stdout and stderr capture don't interfere with each other. +TEST(CaptureTest, CapturesStdoutAndStderr) { + CaptureStdout(); + CaptureStderr(); + fprintf(stdout, "pqr"); + fprintf(stderr, "stu"); + EXPECT_STREQ("pqr", GetCapturedStdout().c_str()); + EXPECT_STREQ("stu", GetCapturedStderr().c_str()); +} + +TEST(CaptureDeathTest, CannotReenterStdoutCapture) { + CaptureStdout(); + EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(), + "Only one stdout capturer can exist at a time"); + GetCapturedStdout(); + + // We cannot test stderr capturing using death tests as they use it + // themselves. +} + +#endif // !GTEST_OS_WINDOWS_MOBILE + +TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) { + ThreadLocal t1; + EXPECT_EQ(0, t1.get()); + + ThreadLocal t2; + EXPECT_TRUE(t2.get() == NULL); +} + +TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) { + ThreadLocal t1(123); + EXPECT_EQ(123, t1.get()); + + int i = 0; + ThreadLocal t2(&i); + EXPECT_EQ(&i, t2.get()); +} + +class NoDefaultContructor { + public: + explicit NoDefaultContructor(const char*) {} + NoDefaultContructor(const NoDefaultContructor&) {} +}; + +TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) { + ThreadLocal bar(NoDefaultContructor("foo")); + bar.pointer(); +} + +TEST(ThreadLocalTest, GetAndPointerReturnSameValue) { + ThreadLocal thread_local_string; + + EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get())); + + // Verifies the condition still holds after calling set. + thread_local_string.set("foo"); + EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get())); +} + +TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) { + ThreadLocal thread_local_string; + const ThreadLocal& const_thread_local_string = + thread_local_string; + + EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer()); + + thread_local_string.set("foo"); + EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer()); +} + +#if GTEST_IS_THREADSAFE + +void AddTwo(int* param) { *param += 2; } + +TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) { + int i = 40; + ThreadWithParam thread(&AddTwo, &i, NULL); + thread.Join(); + EXPECT_EQ(42, i); +} + +TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) { + // AssertHeld() is flaky only in the presence of multiple threads accessing + // the lock. In this case, the test is robust. + EXPECT_DEATH_IF_SUPPORTED({ + Mutex m; + { MutexLock lock(&m); } + m.AssertHeld(); + }, + "thread .*hold"); +} + +TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) { + Mutex m; + MutexLock lock(&m); + m.AssertHeld(); +} + +class AtomicCounterWithMutex { + public: + explicit AtomicCounterWithMutex(Mutex* mutex) : + value_(0), mutex_(mutex), random_(42) {} + + void Increment() { + MutexLock lock(mutex_); + int temp = value_; + { + // We need to put up a memory barrier to prevent reads and writes to + // value_ rearranged with the call to SleepMilliseconds when observed + // from other threads. +#if GTEST_HAS_PTHREAD + // On POSIX, locking a mutex puts up a memory barrier. We cannot use + // Mutex and MutexLock here or rely on their memory barrier + // functionality as we are testing them here. + pthread_mutex_t memory_barrier_mutex; + GTEST_CHECK_POSIX_SUCCESS_( + pthread_mutex_init(&memory_barrier_mutex, NULL)); + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex)); + + SleepMilliseconds(random_.Generate(30)); + + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex)); + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex)); +#elif GTEST_OS_WINDOWS + // On Windows, performing an interlocked access puts up a memory barrier. + volatile LONG dummy = 0; + ::InterlockedIncrement(&dummy); + SleepMilliseconds(random_.Generate(30)); + ::InterlockedIncrement(&dummy); +#else +# error "Memory barrier not implemented on this platform." +#endif // GTEST_HAS_PTHREAD + } + value_ = temp + 1; + } + int value() const { return value_; } + + private: + volatile int value_; + Mutex* const mutex_; // Protects value_. + Random random_; +}; + +void CountingThreadFunc(pair param) { + for (int i = 0; i < param.second; ++i) + param.first->Increment(); +} + +// Tests that the mutex only lets one thread at a time to lock it. +TEST(MutexTest, OnlyOneThreadCanLockAtATime) { + Mutex mutex; + AtomicCounterWithMutex locked_counter(&mutex); + + typedef ThreadWithParam > ThreadType; + const int kCycleCount = 20; + const int kThreadCount = 7; + scoped_ptr counting_threads[kThreadCount]; + Notification threads_can_start; + // Creates and runs kThreadCount threads that increment locked_counter + // kCycleCount times each. + for (int i = 0; i < kThreadCount; ++i) { + counting_threads[i].reset(new ThreadType(&CountingThreadFunc, + make_pair(&locked_counter, + kCycleCount), + &threads_can_start)); + } + threads_can_start.Notify(); + for (int i = 0; i < kThreadCount; ++i) + counting_threads[i]->Join(); + + // If the mutex lets more than one thread to increment the counter at a + // time, they are likely to encounter a race condition and have some + // increments overwritten, resulting in the lower then expected counter + // value. + EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value()); +} + +template +void RunFromThread(void (func)(T), T param) { + ThreadWithParam thread(func, param, NULL); + thread.Join(); +} + +void RetrieveThreadLocalValue( + pair*, std::string*> param) { + *param.second = param.first->get(); +} + +TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) { + ThreadLocal thread_local_string("foo"); + EXPECT_STREQ("foo", thread_local_string.get().c_str()); + + thread_local_string.set("bar"); + EXPECT_STREQ("bar", thread_local_string.get().c_str()); + + std::string result; + RunFromThread(&RetrieveThreadLocalValue, + make_pair(&thread_local_string, &result)); + EXPECT_STREQ("foo", result.c_str()); +} + +// Keeps track of whether of destructors being called on instances of +// DestructorTracker. On Windows, waits for the destructor call reports. +class DestructorCall { + public: + DestructorCall() { + invoked_ = false; +#if GTEST_OS_WINDOWS + wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL)); + GTEST_CHECK_(wait_event_.Get() != NULL); +#endif + } + + bool CheckDestroyed() const { +#if GTEST_OS_WINDOWS + if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0) + return false; +#endif + return invoked_; + } + + void ReportDestroyed() { + invoked_ = true; +#if GTEST_OS_WINDOWS + ::SetEvent(wait_event_.Get()); +#endif + } + + static std::vector& List() { return *list_; } + + static void ResetList() { + for (size_t i = 0; i < list_->size(); ++i) { + delete list_->at(i); + } + list_->clear(); + } + + private: + bool invoked_; +#if GTEST_OS_WINDOWS + AutoHandle wait_event_; +#endif + static std::vector* const list_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall); +}; + +std::vector* const DestructorCall::list_ = + new std::vector; + +// DestructorTracker keeps track of whether its instances have been +// destroyed. +class DestructorTracker { + public: + DestructorTracker() : index_(GetNewIndex()) {} + DestructorTracker(const DestructorTracker& /* rhs */) + : index_(GetNewIndex()) {} + ~DestructorTracker() { + // We never access DestructorCall::List() concurrently, so we don't need + // to protect this access with a mutex. + DestructorCall::List()[index_]->ReportDestroyed(); + } + + private: + static size_t GetNewIndex() { + DestructorCall::List().push_back(new DestructorCall); + return DestructorCall::List().size() - 1; + } + const size_t index_; + + GTEST_DISALLOW_ASSIGN_(DestructorTracker); +}; + +typedef ThreadLocal* ThreadParam; + +void CallThreadLocalGet(ThreadParam thread_local_param) { + thread_local_param->get(); +} + +// Tests that when a ThreadLocal object dies in a thread, it destroys +// the managed object for that thread. +TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) { + DestructorCall::ResetList(); + + { + ThreadLocal thread_local_tracker; + ASSERT_EQ(0U, DestructorCall::List().size()); + + // This creates another DestructorTracker object for the main thread. + thread_local_tracker.get(); + ASSERT_EQ(1U, DestructorCall::List().size()); + ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed()); + } + + // Now thread_local_tracker has died. + ASSERT_EQ(1U, DestructorCall::List().size()); + EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); + + DestructorCall::ResetList(); +} + +// Tests that when a thread exits, the thread-local object for that +// thread is destroyed. +TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) { + DestructorCall::ResetList(); + + { + ThreadLocal thread_local_tracker; + ASSERT_EQ(0U, DestructorCall::List().size()); + + // This creates another DestructorTracker object in the new thread. + ThreadWithParam thread( + &CallThreadLocalGet, &thread_local_tracker, NULL); + thread.Join(); + + // The thread has exited, and we should have a DestroyedTracker + // instance created for it. But it may not have been destroyed yet. + ASSERT_EQ(1U, DestructorCall::List().size()); + } + + // The thread has exited and thread_local_tracker has died. + ASSERT_EQ(1U, DestructorCall::List().size()); + EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); + + DestructorCall::ResetList(); +} + +TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) { + ThreadLocal thread_local_string; + thread_local_string.set("Foo"); + EXPECT_STREQ("Foo", thread_local_string.get().c_str()); + + std::string result; + RunFromThread(&RetrieveThreadLocalValue, + make_pair(&thread_local_string, &result)); + EXPECT_TRUE(result.empty()); +} + +#endif // GTEST_IS_THREADSAFE + +#if GTEST_OS_WINDOWS +TEST(WindowsTypesTest, HANDLEIsVoidStar) { + StaticAssertTypeEq(); +} + +#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) +TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) { + StaticAssertTypeEq(); +} +#else +TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) { + StaticAssertTypeEq(); +} +#endif + +#endif // GTEST_OS_WINDOWS + +} // namespace internal +} // namespace testing diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc new file mode 100644 index 0000000..49b3bd4 --- /dev/null +++ b/googletest/test/googletest-printers-test.cc @@ -0,0 +1,1737 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Test - The Google C++ Testing and Mocking Framework +// +// This file tests the universal value printer. + +#include "gtest/gtest-printers.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gtest/gtest.h" + +#if GTEST_HAS_UNORDERED_MAP_ +# include // NOLINT +#endif // GTEST_HAS_UNORDERED_MAP_ + +#if GTEST_HAS_UNORDERED_SET_ +# include // NOLINT +#endif // GTEST_HAS_UNORDERED_SET_ + +#if GTEST_HAS_STD_FORWARD_LIST_ +# include // NOLINT +#endif // GTEST_HAS_STD_FORWARD_LIST_ + +// 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 +class UnprintableTemplateInGlobal { + public: + UnprintableTemplateInGlobal() : value_() {} + private: + T value_; +}; + +// A user-defined streamable type in the global namespace. +class StreamableInGlobal { + public: + virtual ~StreamableInGlobal() {} +}; + +inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) { + os << "StreamableInGlobal"; +} + +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() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); } + double z() const { return z_; } + private: + char xy_[8]; + double z_; +}; + +// A user-defined printable type in a user-chosen namespace. +struct PrintableViaPrintTo { + PrintableViaPrintTo() : value() {} + int value; +}; + +void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) { + *os << "PrintableViaPrintTo: " << x.value; +} + +// A 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 +class PrintableViaPrintToTemplate { + public: + explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {} + + const T& value() const { return value_; } + private: + T value_; +}; + +template +void PrintTo(const PrintableViaPrintToTemplate& x, ::std::ostream* os) { + *os << "PrintableViaPrintToTemplate: " << x.value(); +} + +// A user-defined streamable class template in a user namespace. +template +class StreamableTemplateInFoo { + public: + StreamableTemplateInFoo() : value_() {} + + const T& value() const { return value_; } + private: + T value_; +}; + +template +inline ::std::ostream& operator<<(::std::ostream& os, + const StreamableTemplateInFoo& x) { + return os << "StreamableTemplateInFoo: " << x.value(); +} + +// A user-defined streamable but recursivly-defined container type in +// a user namespace, it mimics therefore std::filesystem::path or +// boost::filesystem::path. +class PathLike { + public: + struct iterator { + typedef PathLike value_type; + }; + + PathLike() {} + + iterator begin() const { return iterator(); } + iterator end() const { return iterator(); } + + friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) { + return os << "Streamable-PathLike"; + } +}; + +} // namespace foo + +namespace testing { +namespace gtest_printers_test { + +using ::std::deque; +using ::std::list; +using ::std::make_pair; +using ::std::map; +using ::std::multimap; +using ::std::multiset; +using ::std::pair; +using ::std::set; +using ::std::vector; +using ::testing::PrintToString; +using ::testing::internal::FormatForComparisonFailureMessage; +using ::testing::internal::ImplicitCast_; +using ::testing::internal::NativeArray; +using ::testing::internal::RE; +using ::testing::internal::RelationToSourceReference; +using ::testing::internal::Strings; +using ::testing::internal::UniversalPrint; +using ::testing::internal::UniversalPrinter; +using ::testing::internal::UniversalTersePrint; +#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ +using ::testing::internal::UniversalTersePrintTupleFieldsToStrings; +#endif + +// Prints a value to a string using the universal value printer. This +// is a helper for testing UniversalPrinter::Print() for various types. +template +std::string Print(const T& value) { + ::std::stringstream ss; + UniversalPrinter::Print(value, &ss); + return ss.str(); +} + +// Prints a value passed by reference to a string, using the universal +// value printer. This is a helper for testing +// UniversalPrinter::Print() for various types. +template +std::string PrintByRef(const T& value) { + ::std::stringstream ss; + UniversalPrinter::Print(value, &ss); + 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(0))); +} + +TEST(PrintEnumTest, EnumWithPrintTo) { + EXPECT_EQ("kEWPT1", Print(kEWPT1)); + EXPECT_EQ("invalid", Print(static_cast(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, 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, 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, 0xB)", Print('\v')); + EXPECT_EQ("'\\x7F' (127)", Print('\x7F')); + EXPECT_EQ("'\\xFF' (255)", Print('\xFF')); + EXPECT_EQ("' ' (32, 0x20)", Print(' ')); + EXPECT_EQ("'a' (97, 0x61)", Print('a')); +} + +// signed char. +TEST(PrintCharTest, SignedChar) { + EXPECT_EQ("'\\0'", Print(static_cast('\0'))); + EXPECT_EQ("'\\xCE' (-50)", + Print(static_cast(-50))); +} + +// unsigned char. +TEST(PrintCharTest, UnsignedChar) { + EXPECT_EQ("'\\0'", Print(static_cast('\0'))); + EXPECT_EQ("'b' (98, 0x62)", + Print(static_cast('b'))); +} + +// Tests printing other simple, built-in types. + +// bool. +TEST(PrintBuiltInTypeTest, Bool) { + EXPECT_EQ("false", Print(false)); + EXPECT_EQ("true", Print(true)); +} + +// wchar_t. +TEST(PrintBuiltInTypeTest, Wchar_t) { + EXPECT_EQ("L'\\0'", Print(L'\0')); + EXPECT_EQ("L'\\'' (39, 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, 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, 0xB)", Print(L'\v')); + EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F')); + EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF')); + EXPECT_EQ("L' ' (32, 0x20)", Print(L' ')); + EXPECT_EQ("L'a' (97, 0x61)", Print(L'a')); + EXPECT_EQ("L'\\x576' (1398)", Print(static_cast(0x576))); + EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast(0xC74D))); +} + +// Test that Int64 provides more storage than wchar_t. +TEST(PrintTypeSizeTest, Wchar_t) { + EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64)); +} + +// Various integer types. +TEST(PrintBuiltInTypeTest, Integer) { + EXPECT_EQ("'\\xFF' (255)", Print(static_cast(255))); // uint8 + EXPECT_EQ("'\\x80' (-128)", Print(static_cast(-128))); // int8 + EXPECT_EQ("65535", Print(USHRT_MAX)); // uint16 + EXPECT_EQ("-32768", Print(SHRT_MIN)); // int16 + EXPECT_EQ("4294967295", Print(UINT_MAX)); // uint32 + EXPECT_EQ("-2147483648", Print(INT_MIN)); // int32 + EXPECT_EQ("18446744073709551615", + Print(static_cast(-1))); // uint64 + EXPECT_EQ("-9223372036854775808", + Print(static_cast(1) << 63)); // int64 +} + +// Size types. +TEST(PrintBuiltInTypeTest, Size_t) { + EXPECT_EQ("1", Print(sizeof('a'))); // size_t. +#if !GTEST_OS_WINDOWS + // Windows has no ssize_t type. + EXPECT_EQ("-2", Print(static_cast(-2))); // ssize_t. +#endif // !GTEST_OS_WINDOWS +} + +// Floating-points. +TEST(PrintBuiltInTypeTest, FloatingPoints) { + EXPECT_EQ("1.5", Print(1.5f)); // float + EXPECT_EQ("-2.5", Print(-2.5)); // double +} + +// Since ::std::stringstream::operator<<(const void *) formats the pointer +// output differently with different compilers, we have to create the expected +// output first and use it as our expectation. +static std::string PrintPointer(const void* p) { + ::std::stringstream expected_result_stream; + expected_result_stream << p; + return expected_result_stream.str(); +} + +// Tests printing C strings. + +// const char*. +TEST(PrintCStringTest, Const) { + const char* p = "World"; + EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p)); +} + +// char*. +TEST(PrintCStringTest, NonConst) { + char p[] = "Hi"; + EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"", + Print(static_cast(p))); +} + +// NULL C string. +TEST(PrintCStringTest, Null) { + const char* p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// Tests that C strings are escaped properly. +TEST(PrintCStringTest, EscapesProperly) { + const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a"; + EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f" + "\\n\\r\\t\\v\\x7F\\xFF a\"", + Print(p)); +} + +// MSVC compiler can be configured to define whar_t as a typedef +// of unsigned short. Defining an overload for const wchar_t* in that case +// would cause pointers to unsigned shorts be printed as wide strings, +// possibly accessing more memory than intended and causing invalid +// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when +// wchar_t is implemented as a native type. +#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) + +// const wchar_t*. +TEST(PrintWideCStringTest, Const) { + const wchar_t* p = L"World"; + EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p)); +} + +// wchar_t*. +TEST(PrintWideCStringTest, NonConst) { + wchar_t p[] = L"Hi"; + EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"", + Print(static_cast(p))); +} + +// NULL wide C string. +TEST(PrintWideCStringTest, Null) { + const wchar_t* p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// Tests that wide C strings are escaped properly. +TEST(PrintWideCStringTest, EscapesProperly) { + const wchar_t 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(static_cast(s))); +} +#endif // native wchar_t + +// Tests printing pointers to other char types. + +// signed char*. +TEST(PrintCharPointerTest, SignedChar) { + signed char* p = reinterpret_cast(0x1234); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// const signed char*. +TEST(PrintCharPointerTest, ConstSignedChar) { + signed char* p = reinterpret_cast(0x1234); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// unsigned char*. +TEST(PrintCharPointerTest, UnsignedChar) { + unsigned char* p = reinterpret_cast(0x1234); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// const unsigned char*. +TEST(PrintCharPointerTest, ConstUnsignedChar) { + const unsigned char* p = reinterpret_cast(0x1234); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// Tests printing pointers to simple, built-in types. + +// bool*. +TEST(PrintPointerToBuiltInTypeTest, Bool) { + bool* p = reinterpret_cast(0xABCD); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// void*. +TEST(PrintPointerToBuiltInTypeTest, Void) { + void* p = reinterpret_cast(0xABCD); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// const void*. +TEST(PrintPointerToBuiltInTypeTest, ConstVoid) { + const void* p = reinterpret_cast(0xABCD); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// Tests printing pointers to pointers. +TEST(PrintPointerToPointerTest, IntPointerPointer) { + int** p = reinterpret_cast(0xABCD); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// Tests printing (non-member) function pointers. + +void MyFunction(int /* n */) {} + +TEST(PrintPointerTest, NonMemberFunctionPointer) { + // We cannot directly cast &MyFunction to const void* because the + // standard disallows casting between pointers to functions and + // pointers to objects, and some compilers (e.g. GCC 3.4) enforce + // this limitation. + EXPECT_EQ( + PrintPointer(reinterpret_cast( + reinterpret_cast(&MyFunction))), + Print(&MyFunction)); + int (*p)(bool) = NULL; // NOLINT + EXPECT_EQ("NULL", Print(p)); +} + +// An assertion predicate determining whether a one string is a prefix for +// another. +template +AssertionResult HasPrefix(const StringType& str, const StringType& prefix) { + if (str.find(prefix, 0) == 0) + return AssertionSuccess(); + + const bool is_wide_string = sizeof(prefix[0]) > 1; + const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; + return AssertionFailure() + << begin_string_quote << prefix << "\" is not a prefix of " + << begin_string_quote << str << "\"\n"; +} + +// Tests printing member variable pointers. Although they are called +// pointers, they don't point to a location in the address space. +// Their representation is implementation-defined. Thus they will be +// printed as raw bytes. + +struct Foo { + public: + virtual ~Foo() {} + int MyMethod(char x) { return x + 1; } + virtual char MyVirtualMethod(int /* n */) { return 'a'; } + + int value; +}; + +TEST(PrintPointerTest, MemberVariablePointer) { + EXPECT_TRUE(HasPrefix(Print(&Foo::value), + Print(sizeof(&Foo::value)) + "-byte object ")); + int (Foo::*p) = NULL; // NOLINT + EXPECT_TRUE(HasPrefix(Print(p), + Print(sizeof(p)) + "-byte object ")); +} + +// Tests printing member function pointers. Although they are called +// pointers, they don't point to a location in the address space. +// Their representation is implementation-defined. Thus they will be +// printed as raw bytes. +TEST(PrintPointerTest, MemberFunctionPointer) { + EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod), + Print(sizeof(&Foo::MyMethod)) + "-byte object ")); + EXPECT_TRUE( + HasPrefix(Print(&Foo::MyVirtualMethod), + Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object ")); + int (Foo::*p)(char) = NULL; // NOLINT + EXPECT_TRUE(HasPrefix(Print(p), + Print(sizeof(p)) + "-byte object ")); +} + +// Tests printing C arrays. + +// The difference between this and Print() is that it ensures that the +// argument is a reference to an array. +template +std::string PrintArrayHelper(T (&a)[N]) { + return Print(a); +} + +// One-dimensional array. +TEST(PrintArrayTest, OneDimensionalArray) { + int a[5] = { 1, 2, 3, 4, 5 }; + EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a)); +} + +// Two-dimensional array. +TEST(PrintArrayTest, TwoDimensionalArray) { + int a[2][5] = { + { 1, 2, 3, 4, 5 }, + { 6, 7, 8, 9, 0 } + }; + EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a)); +} + +// Array of const elements. +TEST(PrintArrayTest, ConstArray) { + const bool a[1] = { false }; + EXPECT_EQ("{ false }", PrintArrayHelper(a)); +} + +// char array without terminating NUL. +TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) { + // Array a contains '\0' in the middle and doesn't end with '\0'. + char a[] = { 'H', '\0', 'i' }; + EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a)); +} + +// const char array with terminating NUL. +TEST(PrintArrayTest, ConstCharArrayWithTerminatingNul) { + const char a[] = "\0Hi"; + EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a)); +} + +// const wchar_t array without terminating NUL. +TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) { + // Array a contains '\0' in the middle and doesn't end with '\0'. + const wchar_t a[] = { L'H', L'\0', L'i' }; + EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a)); +} + +// wchar_t array with terminating NUL. +TEST(PrintArrayTest, WConstCharArrayWithTerminatingNul) { + const wchar_t a[] = L"\0Hi"; + EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a)); +} + +// Array of objects. +TEST(PrintArrayTest, ObjectArray) { + std::string a[3] = {"Hi", "Hello", "Ni hao"}; + EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a)); +} + +// Array with many elements. +TEST(PrintArrayTest, BigArray) { + int a[100] = { 1, 2, 3 }; + EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }", + PrintArrayHelper(a)); +} + +// Tests printing ::string and ::std::string. + +#if GTEST_HAS_GLOBAL_STRING +// ::string. +TEST(PrintStringTest, StringInGlobalNamespace) { + const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; + const ::string str(s, sizeof(s)); + EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"", + Print(str)); +} +#endif // GTEST_HAS_GLOBAL_STRING + +// ::std::string. +TEST(PrintStringTest, StringInStdNamespace) { + const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; + const ::std::string str(s, sizeof(s)); + EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"", + Print(str)); +} + +TEST(PrintStringTest, StringAmbiguousHex) { + // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of: + // '\x6', '\x6B', or '\x6BA'. + + // a hex escaping sequence following by a decimal digit + EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3"))); + // a hex escaping sequence following by a hex digit (lower-case) + EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas"))); + // a hex escaping sequence following by a hex digit (upper-case) + EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA"))); + // a hex escaping sequence following by a non-xdigit + EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!"))); +} + +// Tests printing ::wstring and ::std::wstring. + +#if GTEST_HAS_GLOBAL_WSTRING +// ::wstring. +TEST(PrintWideStringTest, StringInGlobalNamespace) { + const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; + const ::wstring str(s, sizeof(s)/sizeof(wchar_t)); + EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" + "\\xD3\\x576\\x8D3\\xC74D a\\0\"", + Print(str)); +} +#endif // GTEST_HAS_GLOBAL_WSTRING + +#if GTEST_HAS_STD_WSTRING +// ::std::wstring. +TEST(PrintWideStringTest, StringInStdNamespace) { + const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; + const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t)); + EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" + "\\xD3\\x576\\x8D3\\xC74D a\\0\"", + Print(str)); +} + +TEST(PrintWideStringTest, StringAmbiguousHex) { + // same for wide strings. + EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3"))); + EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", + Print(::std::wstring(L"mm\x6" L"bananas"))); + EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", + Print(::std::wstring(L"NOM\x6" L"BANANA"))); + EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!"))); +} +#endif // GTEST_HAS_STD_WSTRING + +// Tests printing types that support generic streaming (i.e. streaming +// to std::basic_ostream for any valid Char and +// CharTraits types). + +// Tests printing a non-template type that supports generic streaming. + +class AllowsGenericStreaming {}; + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, + const AllowsGenericStreaming& /* a */) { + return os << "AllowsGenericStreaming"; +} + +TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) { + AllowsGenericStreaming a; + EXPECT_EQ("AllowsGenericStreaming", Print(a)); +} + +// Tests printing a template type that supports generic streaming. + +template +class AllowsGenericStreamingTemplate {}; + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, + const AllowsGenericStreamingTemplate& /* a */) { + return os << "AllowsGenericStreamingTemplate"; +} + +TEST(PrintTypeWithGenericStreamingTest, TemplateType) { + AllowsGenericStreamingTemplate a; + EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a)); +} + +// Tests printing a type that supports generic streaming and can be +// implicitly converted to another printable type. + +template +class AllowsGenericStreamingAndImplicitConversionTemplate { + public: + operator bool() const { return false; } +}; + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, + const AllowsGenericStreamingAndImplicitConversionTemplate& /* a */) { + return os << "AllowsGenericStreamingAndImplicitConversionTemplate"; +} + +TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) { + AllowsGenericStreamingAndImplicitConversionTemplate a; + EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a)); +} + +#if GTEST_HAS_ABSL + +// Tests printing ::absl::string_view. + +TEST(PrintStringViewTest, SimpleStringView) { + const ::absl::string_view sp = "Hello"; + EXPECT_EQ("\"Hello\"", Print(sp)); +} + +TEST(PrintStringViewTest, UnprintableCharacters) { + const char str[] = "NUL (\0) and \r\t"; + const ::absl::string_view sp(str, sizeof(str) - 1); + EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp)); +} + +#endif // GTEST_HAS_ABSL + +// Tests printing STL containers. + +TEST(PrintStlContainerTest, EmptyDeque) { + deque empty; + EXPECT_EQ("{}", Print(empty)); +} + +TEST(PrintStlContainerTest, NonEmptyDeque) { + deque non_empty; + non_empty.push_back(1); + non_empty.push_back(3); + EXPECT_EQ("{ 1, 3 }", Print(non_empty)); +} + +#if GTEST_HAS_UNORDERED_MAP_ + +TEST(PrintStlContainerTest, OneElementHashMap) { + ::std::unordered_map map1; + map1[1] = 'a'; + EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1)); +} + +TEST(PrintStlContainerTest, HashMultiMap) { + ::std::unordered_multimap map1; + map1.insert(make_pair(5, true)); + map1.insert(make_pair(5, false)); + + // Elements of hash_multimap can be printed in any order. + const std::string result = Print(map1); + EXPECT_TRUE(result == "{ (5, true), (5, false) }" || + result == "{ (5, false), (5, true) }") + << " where Print(map1) returns \"" << result << "\"."; +} + +#endif // GTEST_HAS_UNORDERED_MAP_ + +#if GTEST_HAS_UNORDERED_SET_ + +TEST(PrintStlContainerTest, HashSet) { + ::std::unordered_set set1; + set1.insert(1); + EXPECT_EQ("{ 1 }", Print(set1)); +} + +TEST(PrintStlContainerTest, HashMultiSet) { + const int kSize = 5; + int a[kSize] = { 1, 1, 2, 5, 1 }; + ::std::unordered_multiset set1(a, a + kSize); + + // Elements of hash_multiset can be printed in any order. + const std::string result = Print(set1); + const std::string expected_pattern = "{ d, d, d, d, d }"; // d means a digit. + + // Verifies the result matches the expected pattern; also extracts + // the numbers in the result. + ASSERT_EQ(expected_pattern.length(), result.length()); + std::vector numbers; + for (size_t i = 0; i != result.length(); i++) { + if (expected_pattern[i] == 'd') { + ASSERT_NE(isdigit(static_cast(result[i])), 0); + numbers.push_back(result[i] - '0'); + } else { + EXPECT_EQ(expected_pattern[i], result[i]) << " where result is " + << result; + } + } + + // Makes sure the result contains the right numbers. + std::sort(numbers.begin(), numbers.end()); + std::sort(a, a + kSize); + EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); +} + +#endif // GTEST_HAS_UNORDERED_SET_ + +TEST(PrintStlContainerTest, List) { + const std::string a[] = {"hello", "world"}; + const list strings(a, a + 2); + EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings)); +} + +TEST(PrintStlContainerTest, Map) { + map map1; + map1[1] = true; + map1[5] = false; + map1[3] = true; + EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1)); +} + +TEST(PrintStlContainerTest, MultiMap) { + multimap map1; + // The make_pair template function would deduce the type as + // pair here, and since the key part in a multimap has to + // be constant, without a templated ctor in the pair class (as in + // libCstd on Solaris), make_pair call would fail to compile as no + // implicit conversion is found. Thus explicit typename is used + // here instead. + map1.insert(pair(true, 0)); + map1.insert(pair(true, 1)); + map1.insert(pair(false, 2)); + EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1)); +} + +TEST(PrintStlContainerTest, Set) { + const unsigned int a[] = { 3, 0, 5 }; + set set1(a, a + 3); + EXPECT_EQ("{ 0, 3, 5 }", Print(set1)); +} + +TEST(PrintStlContainerTest, MultiSet) { + const int a[] = { 1, 1, 2, 5, 1 }; + multiset set1(a, a + 5); + EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1)); +} + +#if GTEST_HAS_STD_FORWARD_LIST_ +// is available on Linux in the google3 mode, but not on +// Windows or Mac OS X. + +TEST(PrintStlContainerTest, SinglyLinkedList) { + int a[] = { 9, 2, 8 }; + const std::forward_list ints(a, a + 3); + EXPECT_EQ("{ 9, 2, 8 }", Print(ints)); +} +#endif // GTEST_HAS_STD_FORWARD_LIST_ + +TEST(PrintStlContainerTest, Pair) { + pair p(true, 5); + EXPECT_EQ("(true, 5)", Print(p)); +} + +TEST(PrintStlContainerTest, Vector) { + vector v; + v.push_back(1); + v.push_back(2); + EXPECT_EQ("{ 1, 2 }", Print(v)); +} + +TEST(PrintStlContainerTest, LongSequence) { + const int a[100] = { 1, 2, 3 }; + const vector v(a, a + 100); + EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v)); +} + +TEST(PrintStlContainerTest, NestedContainer) { + const int a1[] = { 1, 2 }; + const int a2[] = { 3, 4, 5 }; + const list l1(a1, a1 + 2); + const list l2(a2, a2 + 3); + + vector > v; + v.push_back(l1); + v.push_back(l2); + EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v)); +} + +TEST(PrintStlContainerTest, OneDimensionalNativeArray) { + const int a[3] = { 1, 2, 3 }; + NativeArray b(a, 3, RelationToSourceReference()); + EXPECT_EQ("{ 1, 2, 3 }", Print(b)); +} + +TEST(PrintStlContainerTest, TwoDimensionalNativeArray) { + const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; + NativeArray b(a, 2, RelationToSourceReference()); + EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b)); +} + +// Tests that a class named iterator isn't treated as a container. + +struct iterator { + char x; +}; + +TEST(PrintStlContainerTest, Iterator) { + iterator it = {}; + EXPECT_EQ("1-byte object <00>", Print(it)); +} + +// Tests that a class named const_iterator isn't treated as a container. + +struct const_iterator { + char x; +}; + +TEST(PrintStlContainerTest, ConstIterator) { + const_iterator it = {}; + EXPECT_EQ("1-byte object <00>", Print(it)); +} + +#if GTEST_HAS_TR1_TUPLE +// Tests printing ::std::tr1::tuples. + +// Tuples of various arities. +TEST(PrintTr1TupleTest, VariousSizes) { + ::std::tr1::tuple<> t0; + EXPECT_EQ("()", Print(t0)); + + ::std::tr1::tuple t1(5); + EXPECT_EQ("(5)", Print(t1)); + + ::std::tr1::tuple t2('a', true); + EXPECT_EQ("('a' (97, 0x61), true)", Print(t2)); + + ::std::tr1::tuple t3(false, 2, 3); + EXPECT_EQ("(false, 2, 3)", Print(t3)); + + ::std::tr1::tuple t4(false, 2, 3, 4); + EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); + + ::std::tr1::tuple t5(false, 2, 3, 4, true); + EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5)); + + ::std::tr1::tuple t6(false, 2, 3, 4, true, 6); + EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6)); + + ::std::tr1::tuple t7( + false, 2, 3, 4, true, 6, 7); + EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7)); + + ::std::tr1::tuple t8( + false, 2, 3, 4, true, 6, 7, true); + EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8)); + + ::std::tr1::tuple t9( + false, 2, 3, 4, true, 6, 7, true, 9); + EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9)); + + const char* const str = "8"; + // VC++ 2010's implementation of tuple of C++0x is deficient, requiring + // an explicit type cast of NULL to be used. + ::std::tr1::tuple + t10(false, 'a', static_cast(3), 4, 5, 1.5F, -2.5, str, // NOLINT + ImplicitCast_(NULL), "10"); + EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + + " pointing to \"8\", NULL, \"10\")", + Print(t10)); +} + +// Nested tuples. +TEST(PrintTr1TupleTest, NestedTuple) { + ::std::tr1::tuple< ::std::tr1::tuple, char> nested( + ::std::tr1::make_tuple(5, true), 'a'); + EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); +} + +#endif // GTEST_HAS_TR1_TUPLE + +#if GTEST_HAS_STD_TUPLE_ +// Tests printing ::std::tuples. + +// Tuples of various arities. +TEST(PrintStdTupleTest, VariousSizes) { + ::std::tuple<> t0; + EXPECT_EQ("()", Print(t0)); + + ::std::tuple t1(5); + EXPECT_EQ("(5)", Print(t1)); + + ::std::tuple t2('a', true); + EXPECT_EQ("('a' (97, 0x61), true)", Print(t2)); + + ::std::tuple t3(false, 2, 3); + EXPECT_EQ("(false, 2, 3)", Print(t3)); + + ::std::tuple t4(false, 2, 3, 4); + EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); + + ::std::tuple t5(false, 2, 3, 4, true); + EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5)); + + ::std::tuple t6(false, 2, 3, 4, true, 6); + EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6)); + + ::std::tuple t7( + false, 2, 3, 4, true, 6, 7); + EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7)); + + ::std::tuple t8( + false, 2, 3, 4, true, 6, 7, true); + EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8)); + + ::std::tuple t9( + false, 2, 3, 4, true, 6, 7, true, 9); + EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9)); + + const char* const str = "8"; + // VC++ 2010's implementation of tuple of C++0x is deficient, requiring + // an explicit type cast of NULL to be used. + ::std::tuple + t10(false, 'a', static_cast(3), 4, 5, 1.5F, -2.5, str, // NOLINT + ImplicitCast_(NULL), "10"); + EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + + " pointing to \"8\", NULL, \"10\")", + Print(t10)); +} + +// Nested tuples. +TEST(PrintStdTupleTest, NestedTuple) { + ::std::tuple< ::std::tuple, char> nested( + ::std::make_tuple(5, true), 'a'); + EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); +} + +#endif // GTEST_LANG_CXX11 + +#if GTEST_LANG_CXX11 +TEST(PrintNullptrT, Basic) { + EXPECT_EQ("(nullptr)", Print(nullptr)); +} +#endif // GTEST_LANG_CXX11 + +// Tests printing user-defined unprintable types. + +// Unprintable types in the global namespace. +TEST(PrintUnprintableTypeTest, InGlobalNamespace) { + EXPECT_EQ("1-byte object <00>", + Print(UnprintableTemplateInGlobal())); +} + +// Unprintable types in a user namespace. +TEST(PrintUnprintableTypeTest, InUserNamespace) { + EXPECT_EQ("16-byte object ", + Print(::foo::UnprintableInFoo())); +} + +// Unprintable types are that too big to be printed completely. + +struct Big { + Big() { memset(array, 0, sizeof(array)); } + char array[257]; +}; + +TEST(PrintUnpritableTypeTest, BigObject) { + EXPECT_EQ("257-byte object <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())); +} + +// Tests printing user-defined streamable types. + +// Streamable types in the global namespace. +TEST(PrintStreamableTypeTest, InGlobalNamespace) { + StreamableInGlobal x; + EXPECT_EQ("StreamableInGlobal", Print(x)); + EXPECT_EQ("StreamableInGlobal*", Print(&x)); +} + +// Printable template types in a user namespace. +TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) { + EXPECT_EQ("StreamableTemplateInFoo: 0", + Print(::foo::StreamableTemplateInFoo())); +} + +// Tests printing a user-defined recursive container type that has a << +// operator. +TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) { + ::foo::PathLike x; + EXPECT_EQ("Streamable-PathLike", Print(x)); + const ::foo::PathLike cx; + EXPECT_EQ("Streamable-PathLike", Print(cx)); +} + +// Tests printing user-defined types that have a PrintTo() function. +TEST(PrintPrintableTypeTest, InUserNamespace) { + EXPECT_EQ("PrintableViaPrintTo: 0", + 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", + Print(::foo::PrintableViaPrintToTemplate(5))); +} + +// Tests that the universal printer prints both the address and the +// value of a reference. +TEST(PrintReferenceTest, PrintsAddressAndValue) { + int n = 5; + EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n)); + + int a[2][3] = { + { 0, 1, 2 }, + { 3, 4, 5 } + }; + EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }", + PrintByRef(a)); + + const ::foo::UnprintableInFoo x; + EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object " + "", + PrintByRef(x)); +} + +// Tests that the universal printer prints a function pointer passed by +// reference. +TEST(PrintReferenceTest, HandlesFunctionPointer) { + void (*fp)(int n) = &MyFunction; + const std::string fp_pointer_string = + PrintPointer(reinterpret_cast(&fp)); + // We cannot directly cast &MyFunction to const void* because the + // standard disallows casting between pointers to functions and + // pointers to objects, and some compilers (e.g. GCC 3.4) enforce + // this limitation. + const std::string fp_string = PrintPointer(reinterpret_cast( + reinterpret_cast(fp))); + EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, + PrintByRef(fp)); +} + +// Tests that the universal printer prints a member function pointer +// passed by reference. +TEST(PrintReferenceTest, HandlesMemberFunctionPointer) { + int (Foo::*p)(char ch) = &Foo::MyMethod; + EXPECT_TRUE(HasPrefix( + PrintByRef(p), + "@" + PrintPointer(reinterpret_cast(&p)) + " " + + Print(sizeof(p)) + "-byte object ")); + + char (Foo::*p2)(int n) = &Foo::MyVirtualMethod; + EXPECT_TRUE(HasPrefix( + PrintByRef(p2), + "@" + PrintPointer(reinterpret_cast(&p2)) + " " + + Print(sizeof(p2)) + "-byte object ")); +} + +// Tests that the universal printer prints a member variable pointer +// passed by reference. +TEST(PrintReferenceTest, HandlesMemberVariablePointer) { + int (Foo::*p) = &Foo::value; // NOLINT + EXPECT_TRUE(HasPrefix( + PrintByRef(p), + "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object ")); +} + +// Tests that FormatForComparisonFailureMessage(), which is used to print +// an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion +// fails, formats the operand in the desired way. + +// scalar +TEST(FormatForComparisonFailureMessageTest, WorksForScalar) { + EXPECT_STREQ("123", + FormatForComparisonFailureMessage(123, 124).c_str()); +} + +// non-char pointer +TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) { + int n = 0; + EXPECT_EQ(PrintPointer(&n), + FormatForComparisonFailureMessage(&n, &n).c_str()); +} + +// non-char array +TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) { + // In expression 'array == x', 'array' is compared by pointer. + // Therefore we want to print an array operand as a pointer. + int n[] = { 1, 2, 3 }; + EXPECT_EQ(PrintPointer(n), + FormatForComparisonFailureMessage(n, n).c_str()); +} + +// Tests formatting a char pointer when it's compared with another pointer. +// In this case we want to print it as a raw pointer, as the comparison is by +// pointer. + +// char pointer vs pointer +TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) { + // In expression 'p == x', where 'p' and 'x' are (const or not) char + // pointers, the operands are compared by pointer. Therefore we + // want to print 'p' as a pointer instead of a C string (we don't + // even know if it's supposed to point to a valid C string). + + // const char* + const char* s = "hello"; + EXPECT_EQ(PrintPointer(s), + FormatForComparisonFailureMessage(s, s).c_str()); + + // char* + char ch = 'a'; + EXPECT_EQ(PrintPointer(&ch), + FormatForComparisonFailureMessage(&ch, &ch).c_str()); +} + +// wchar_t pointer vs pointer +TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) { + // In expression 'p == x', where 'p' and 'x' are (const or not) char + // pointers, the operands are compared by pointer. Therefore we + // want to print 'p' as a pointer instead of a wide C string (we don't + // even know if it's supposed to point to a valid wide C string). + + // const wchar_t* + const wchar_t* s = L"hello"; + EXPECT_EQ(PrintPointer(s), + FormatForComparisonFailureMessage(s, s).c_str()); + + // wchar_t* + wchar_t ch = L'a'; + EXPECT_EQ(PrintPointer(&ch), + FormatForComparisonFailureMessage(&ch, &ch).c_str()); +} + +// Tests formatting a char pointer when it's compared to a string object. +// In this case we want to print the char pointer as a C string. + +#if GTEST_HAS_GLOBAL_STRING +// char pointer vs ::string +TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsString) { + const char* s = "hello \"world"; + EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped. + FormatForComparisonFailureMessage(s, ::string()).c_str()); + + // char* + char str[] = "hi\1"; + char* p = str; + EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped. + FormatForComparisonFailureMessage(p, ::string()).c_str()); +} +#endif + +// char pointer vs std::string +TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) { + const char* s = "hello \"world"; + EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped. + FormatForComparisonFailureMessage(s, ::std::string()).c_str()); + + // char* + char str[] = "hi\1"; + char* p = str; + EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped. + FormatForComparisonFailureMessage(p, ::std::string()).c_str()); +} + +#if GTEST_HAS_GLOBAL_WSTRING +// wchar_t pointer vs ::wstring +TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsWString) { + const wchar_t* s = L"hi \"world"; + EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped. + FormatForComparisonFailureMessage(s, ::wstring()).c_str()); + + // wchar_t* + wchar_t str[] = L"hi\1"; + wchar_t* p = str; + EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped. + FormatForComparisonFailureMessage(p, ::wstring()).c_str()); +} +#endif + +#if GTEST_HAS_STD_WSTRING +// wchar_t pointer vs std::wstring +TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) { + const wchar_t* s = L"hi \"world"; + EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped. + FormatForComparisonFailureMessage(s, ::std::wstring()).c_str()); + + // wchar_t* + wchar_t str[] = L"hi\1"; + wchar_t* p = str; + EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped. + FormatForComparisonFailureMessage(p, ::std::wstring()).c_str()); +} +#endif + +// Tests formatting a char array when it's compared with a pointer or array. +// In this case we want to print the array as a row pointer, as the comparison +// is by pointer. + +// char array vs pointer +TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) { + char str[] = "hi \"world\""; + char* p = NULL; + EXPECT_EQ(PrintPointer(str), + FormatForComparisonFailureMessage(str, p).c_str()); +} + +// char array vs char array +TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) { + const char str[] = "hi \"world\""; + EXPECT_EQ(PrintPointer(str), + FormatForComparisonFailureMessage(str, str).c_str()); +} + +// wchar_t array vs pointer +TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) { + wchar_t str[] = L"hi \"world\""; + wchar_t* p = NULL; + EXPECT_EQ(PrintPointer(str), + FormatForComparisonFailureMessage(str, p).c_str()); +} + +// wchar_t array vs wchar_t array +TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) { + const wchar_t str[] = L"hi \"world\""; + EXPECT_EQ(PrintPointer(str), + FormatForComparisonFailureMessage(str, str).c_str()); +} + +// Tests formatting a char array when it's compared with a string object. +// In this case we want to print the array as a C string. + +#if GTEST_HAS_GLOBAL_STRING +// char array vs string +TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsString) { + const char str[] = "hi \"w\0rld\""; + EXPECT_STREQ("\"hi \\\"w\"", // The content should be escaped. + // Embedded NUL terminates the string. + FormatForComparisonFailureMessage(str, ::string()).c_str()); +} +#endif + +// char array vs std::string +TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) { + const char str[] = "hi \"world\""; + EXPECT_STREQ("\"hi \\\"world\\\"\"", // The content should be escaped. + FormatForComparisonFailureMessage(str, ::std::string()).c_str()); +} + +#if GTEST_HAS_GLOBAL_WSTRING +// wchar_t array vs wstring +TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWString) { + const wchar_t str[] = L"hi \"world\""; + EXPECT_STREQ("L\"hi \\\"world\\\"\"", // The content should be escaped. + FormatForComparisonFailureMessage(str, ::wstring()).c_str()); +} +#endif + +#if GTEST_HAS_STD_WSTRING +// wchar_t array vs std::wstring +TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) { + const wchar_t str[] = L"hi \"w\0rld\""; + EXPECT_STREQ( + "L\"hi \\\"w\"", // The content should be escaped. + // Embedded NUL terminates the string. + FormatForComparisonFailureMessage(str, ::std::wstring()).c_str()); +} +#endif + +// 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_PRINT_TO_STRING_(123, "123"); +} + +TEST(PrintToStringTest, WorksForPointerToConstChar) { + const char* p = "hello"; + EXPECT_PRINT_TO_STRING_(p, "\"hello\""); +} + +TEST(PrintToStringTest, WorksForPointerToNonConstChar) { + char s[] = "hello"; + char* p = s; + EXPECT_PRINT_TO_STRING_(p, "\"hello\""); +} + +TEST(PrintToStringTest, EscapesForPointerToConstChar) { + const char* p = "hello\n"; + EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\""); +} + +TEST(PrintToStringTest, EscapesForPointerToNonConstChar) { + char s[] = "hello\1"; + char* p = s; + EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\""); +} + +TEST(PrintToStringTest, WorksForArray) { + int n[3] = { 1, 2, 3 }; + EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }"); +} + +TEST(PrintToStringTest, WorksForCharArray) { + char s[] = "hello"; + EXPECT_PRINT_TO_STRING_(s, "\"hello\""); +} + +TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) { + const char str_with_nul[] = "hello\0 world"; + EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\""); + + char mutable_str_with_nul[] = "hello\0 world"; + EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\""); +} + + TEST(PrintToStringTest, ContainsNonLatin) { + // Sanity test with valid UTF-8. Prints both in hex and as text. + std::string non_ascii_str = ::std::string("오전 4:30"); + EXPECT_PRINT_TO_STRING_(non_ascii_str, + "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n" + " As Text: \"오전 4:30\""); + non_ascii_str = ::std::string("From ä — ẑ"); + EXPECT_PRINT_TO_STRING_(non_ascii_str, + "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\"" + "\n As Text: \"From ä — ẑ\""); +} + +TEST(IsValidUTF8Test, IllFormedUTF8) { + // The following test strings are ill-formed UTF-8 and are printed + // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is + // expected to fail, thus output does not contain "As Text:". + + static const char *const kTestdata[][2] = { + // 2-byte lead byte followed by a single-byte character. + {"\xC3\x74", "\"\\xC3t\""}, + // Valid 2-byte character followed by an orphan trail byte. + {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""}, + // Lead byte without trail byte. + {"abc\xC3", "\"abc\\xC3\""}, + // 3-byte lead byte, single-byte character, orphan trail byte. + {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""}, + // Truncated 3-byte character. + {"\xE2\x80", "\"\\xE2\\x80\""}, + // Truncated 3-byte character followed by valid 2-byte char. + {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""}, + // Truncated 3-byte character followed by a single-byte character. + {"\xE2\x80\x7A", "\"\\xE2\\x80z\""}, + // 3-byte lead byte followed by valid 3-byte character. + {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""}, + // 4-byte lead byte followed by valid 3-byte character. + {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""}, + // Truncated 4-byte character. + {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""}, + // Invalid UTF-8 byte sequences embedded in other chars. + {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""}, + {"abc\xC3\x84\xE2\x80\xC3\x84xyz", + "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""}, + // Non-shortest UTF-8 byte sequences are also ill-formed. + // The classics: xC0, xC1 lead byte. + {"\xC0\x80", "\"\\xC0\\x80\""}, + {"\xC1\x81", "\"\\xC1\\x81\""}, + // Non-shortest sequences. + {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""}, + {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""}, + // Last valid code point before surrogate range, should be printed as text, + // too. + {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"퟿\""}, + // Start of surrogate lead. Surrogates are not printed as text. + {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""}, + // Last non-private surrogate lead. + {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""}, + // First private-use surrogate lead. + {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""}, + // Last private-use surrogate lead. + {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""}, + // Mid-point of surrogate trail. + {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""}, + // First valid code point after surrogate range, should be printed as text, + // too. + {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""} + }; + + for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) { + EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]); + } +} + +#undef EXPECT_PRINT_TO_STRING_ + +TEST(UniversalTersePrintTest, WorksForNonReference) { + ::std::stringstream ss; + UniversalTersePrint(123, &ss); + EXPECT_EQ("123", ss.str()); +} + +TEST(UniversalTersePrintTest, WorksForReference) { + const int& n = 123; + ::std::stringstream ss; + UniversalTersePrint(n, &ss); + EXPECT_EQ("123", ss.str()); +} + +TEST(UniversalTersePrintTest, WorksForCString) { + const char* s1 = "abc"; + ::std::stringstream ss1; + UniversalTersePrint(s1, &ss1); + EXPECT_EQ("\"abc\"", ss1.str()); + + char* s2 = const_cast(s1); + ::std::stringstream ss2; + UniversalTersePrint(s2, &ss2); + EXPECT_EQ("\"abc\"", ss2.str()); + + const char* s3 = NULL; + ::std::stringstream ss3; + UniversalTersePrint(s3, &ss3); + EXPECT_EQ("NULL", ss3.str()); +} + +TEST(UniversalPrintTest, WorksForNonReference) { + ::std::stringstream ss; + UniversalPrint(123, &ss); + EXPECT_EQ("123", ss.str()); +} + +TEST(UniversalPrintTest, WorksForReference) { + const int& n = 123; + ::std::stringstream ss; + UniversalPrint(n, &ss); + EXPECT_EQ("123", ss.str()); +} + +TEST(UniversalPrintTest, WorksForCString) { + const char* s1 = "abc"; + ::std::stringstream ss1; + UniversalPrint(s1, &ss1); + EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str())); + + char* s2 = const_cast(s1); + ::std::stringstream ss2; + UniversalPrint(s2, &ss2); + EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str())); + + const char* s3 = NULL; + ::std::stringstream ss3; + UniversalPrint(s3, &ss3); + EXPECT_EQ("NULL", ss3.str()); +} + +TEST(UniversalPrintTest, WorksForCharArray) { + const char str[] = "\"Line\0 1\"\nLine 2"; + ::std::stringstream ss1; + UniversalPrint(str, &ss1); + EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str()); + + const char mutable_str[] = "\"Line\0 1\"\nLine 2"; + ::std::stringstream ss2; + UniversalPrint(mutable_str, &ss2); + EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str()); +} + +#if GTEST_HAS_TR1_TUPLE + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsEmptyTuple) { + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::tr1::make_tuple()); + EXPECT_EQ(0u, result.size()); +} + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsOneTuple) { + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::tr1::make_tuple(1)); + ASSERT_EQ(1u, result.size()); + EXPECT_EQ("1", result[0]); +} + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTwoTuple) { + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::tr1::make_tuple(1, 'a')); + ASSERT_EQ(2u, result.size()); + EXPECT_EQ("1", result[0]); + EXPECT_EQ("'a' (97, 0x61)", result[1]); +} + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTersely) { + const int n = 1; + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::tr1::tuple(n, "a")); + ASSERT_EQ(2u, result.size()); + EXPECT_EQ("1", result[0]); + EXPECT_EQ("\"a\"", result[1]); +} + +#endif // GTEST_HAS_TR1_TUPLE + +#if GTEST_HAS_STD_TUPLE_ + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) { + Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple()); + EXPECT_EQ(0u, result.size()); +} + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) { + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::make_tuple(1)); + ASSERT_EQ(1u, result.size()); + EXPECT_EQ("1", result[0]); +} + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) { + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::make_tuple(1, 'a')); + ASSERT_EQ(2u, result.size()); + EXPECT_EQ("1", result[0]); + EXPECT_EQ("'a' (97, 0x61)", result[1]); +} + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) { + const int n = 1; + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::tuple(n, "a")); + ASSERT_EQ(2u, result.size()); + EXPECT_EQ("1", result[0]); + EXPECT_EQ("\"a\"", result[1]); +} + +#endif // GTEST_HAS_STD_TUPLE_ + +#if GTEST_HAS_ABSL + +TEST(PrintOptionalTest, Basic) { + absl::optional value; + EXPECT_EQ("(nullopt)", PrintToString(value)); + value = {7}; + EXPECT_EQ("(7)", PrintToString(value)); + EXPECT_EQ("(1.1)", PrintToString(absl::optional{1.1})); + EXPECT_EQ("(\"A\")", PrintToString(absl::optional{"A"})); +} +#endif // GTEST_HAS_ABSL + +} // namespace gtest_printers_test +} // namespace testing diff --git a/googletest/test/googletest-tuple-test.cc b/googletest/test/googletest-tuple-test.cc new file mode 100644 index 0000000..bfaa3e0 --- /dev/null +++ b/googletest/test/googletest-tuple-test.cc @@ -0,0 +1,320 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +#include "gtest/internal/gtest-tuple.h" +#include +#include "gtest/gtest.h" + +namespace { + +using ::std::tr1::get; +using ::std::tr1::make_tuple; +using ::std::tr1::tuple; +using ::std::tr1::tuple_element; +using ::std::tr1::tuple_size; +using ::testing::StaticAssertTypeEq; + +// Tests that tuple_element >::type returns TK. +TEST(tuple_element_Test, ReturnsElementType) { + StaticAssertTypeEq >::type>(); + StaticAssertTypeEq >::type>(); + StaticAssertTypeEq >::type>(); +} + +// Tests that tuple_size::value gives the number of fields in tuple +// type T. +TEST(tuple_size_Test, ReturnsNumberOfFields) { + EXPECT_EQ(0, +tuple_size >::value); + EXPECT_EQ(1, +tuple_size >::value); + EXPECT_EQ(1, +tuple_size >::value); + EXPECT_EQ(1, +(tuple_size > >::value)); + EXPECT_EQ(2, +(tuple_size >::value)); + EXPECT_EQ(3, +(tuple_size >::value)); +} + +// Tests comparing a tuple with itself. +TEST(ComparisonTest, ComparesWithSelf) { + const tuple a(5, 'a', false); + + EXPECT_TRUE(a == a); + EXPECT_FALSE(a != a); +} + +// Tests comparing two tuples with the same value. +TEST(ComparisonTest, ComparesEqualTuples) { + const tuple a(5, true), b(5, true); + + EXPECT_TRUE(a == b); + EXPECT_FALSE(a != b); +} + +// Tests comparing two different tuples that have no reference fields. +TEST(ComparisonTest, ComparesUnequalTuplesWithoutReferenceFields) { + typedef tuple FooTuple; + + const FooTuple a(0, 'x'); + const FooTuple b(1, 'a'); + + EXPECT_TRUE(a != b); + EXPECT_FALSE(a == b); + + const FooTuple c(1, 'b'); + + EXPECT_TRUE(b != c); + EXPECT_FALSE(b == c); +} + +// Tests comparing two different tuples that have reference fields. +TEST(ComparisonTest, ComparesUnequalTuplesWithReferenceFields) { + typedef tuple FooTuple; + + int i = 5; + const char ch = 'a'; + const FooTuple a(i, ch); + + int j = 6; + const FooTuple b(j, ch); + + EXPECT_TRUE(a != b); + EXPECT_FALSE(a == b); + + j = 5; + const char ch2 = 'b'; + const FooTuple c(j, ch2); + + EXPECT_TRUE(b != c); + EXPECT_FALSE(b == c); +} + +// Tests that a tuple field with a reference type is an alias of the +// variable it's supposed to reference. +TEST(ReferenceFieldTest, IsAliasOfReferencedVariable) { + int n = 0; + tuple t(true, n); + + n = 1; + EXPECT_EQ(n, get<1>(t)) + << "Changing a underlying variable should update the reference field."; + + // Makes sure that the implementation doesn't do anything funny with + // the & operator for the return type of get<>(). + EXPECT_EQ(&n, &(get<1>(t))) + << "The address of a reference field should equal the address of " + << "the underlying variable."; + + get<1>(t) = 2; + EXPECT_EQ(2, n) + << "Changing a reference field should update the underlying variable."; +} + +// Tests that tuple's default constructor default initializes each field. +// This test needs to compile without generating warnings. +TEST(TupleConstructorTest, DefaultConstructorDefaultInitializesEachField) { + // The TR1 report requires that tuple's default constructor default + // initializes each field, even if it's a primitive type. If the + // implementation forgets to do this, this test will catch it by + // generating warnings about using uninitialized variables (assuming + // a decent compiler). + + tuple<> empty; + + tuple a1, b1; + b1 = a1; + EXPECT_EQ(0, get<0>(b1)); + + tuple a2, b2; + b2 = a2; + EXPECT_EQ(0, get<0>(b2)); + EXPECT_EQ(0.0, get<1>(b2)); + + tuple a3, b3; + b3 = a3; + EXPECT_EQ(0.0, get<0>(b3)); + EXPECT_EQ('\0', get<1>(b3)); + EXPECT_TRUE(get<2>(b3) == NULL); + + tuple a10, b10; + b10 = a10; + EXPECT_EQ(0, get<0>(b10)); + EXPECT_EQ(0, get<1>(b10)); + EXPECT_EQ(0, get<2>(b10)); + EXPECT_EQ(0, get<3>(b10)); + EXPECT_EQ(0, get<4>(b10)); + EXPECT_EQ(0, get<5>(b10)); + EXPECT_EQ(0, get<6>(b10)); + EXPECT_EQ(0, get<7>(b10)); + EXPECT_EQ(0, get<8>(b10)); + EXPECT_EQ(0, get<9>(b10)); +} + +// Tests constructing a tuple from its fields. +TEST(TupleConstructorTest, ConstructsFromFields) { + int n = 1; + // Reference field. + tuple a(n); + EXPECT_EQ(&n, &(get<0>(a))); + + // Non-reference fields. + tuple b(5, 'a'); + EXPECT_EQ(5, get<0>(b)); + EXPECT_EQ('a', get<1>(b)); + + // Const reference field. + const int m = 2; + tuple c(true, m); + EXPECT_TRUE(get<0>(c)); + EXPECT_EQ(&m, &(get<1>(c))); +} + +// Tests tuple's copy constructor. +TEST(TupleConstructorTest, CopyConstructor) { + tuple a(0.0, true); + tuple b(a); + + EXPECT_DOUBLE_EQ(0.0, get<0>(b)); + EXPECT_TRUE(get<1>(b)); +} + +// Tests constructing a tuple from another tuple that has a compatible +// but different type. +TEST(TupleConstructorTest, ConstructsFromDifferentTupleType) { + tuple a(0, 1, 'a'); + tuple b(a); + + EXPECT_DOUBLE_EQ(0.0, get<0>(b)); + EXPECT_EQ(1, get<1>(b)); + EXPECT_EQ('a', get<2>(b)); +} + +// Tests constructing a 2-tuple from an std::pair. +TEST(TupleConstructorTest, ConstructsFromPair) { + ::std::pair a(1, 'a'); + tuple b(a); + tuple c(a); +} + +// Tests assigning a tuple to another tuple with the same type. +TEST(TupleAssignmentTest, AssignsToSameTupleType) { + const tuple a(5, 7L); + tuple b; + b = a; + EXPECT_EQ(5, get<0>(b)); + EXPECT_EQ(7L, get<1>(b)); +} + +// Tests assigning a tuple to another tuple with a different but +// compatible type. +TEST(TupleAssignmentTest, AssignsToDifferentTupleType) { + const tuple a(1, 7L, true); + tuple b; + b = a; + EXPECT_EQ(1L, get<0>(b)); + EXPECT_EQ(7, get<1>(b)); + EXPECT_TRUE(get<2>(b)); +} + +// Tests assigning an std::pair to a 2-tuple. +TEST(TupleAssignmentTest, AssignsFromPair) { + const ::std::pair a(5, true); + tuple b; + b = a; + EXPECT_EQ(5, get<0>(b)); + EXPECT_TRUE(get<1>(b)); + + tuple c; + c = a; + EXPECT_EQ(5L, get<0>(c)); + EXPECT_TRUE(get<1>(c)); +} + +// A fixture for testing big tuples. +class BigTupleTest : public testing::Test { + protected: + typedef tuple BigTuple; + + BigTupleTest() : + a_(1, 0, 0, 0, 0, 0, 0, 0, 0, 2), + b_(1, 0, 0, 0, 0, 0, 0, 0, 0, 3) {} + + BigTuple a_, b_; +}; + +// Tests constructing big tuples. +TEST_F(BigTupleTest, Construction) { + BigTuple a; + BigTuple b(b_); +} + +// Tests that get(t) returns the N-th (0-based) field of tuple t. +TEST_F(BigTupleTest, get) { + EXPECT_EQ(1, get<0>(a_)); + EXPECT_EQ(2, get<9>(a_)); + + // Tests that get() works on a const tuple too. + const BigTuple a(a_); + EXPECT_EQ(1, get<0>(a)); + EXPECT_EQ(2, get<9>(a)); +} + +// Tests comparing big tuples. +TEST_F(BigTupleTest, Comparisons) { + EXPECT_TRUE(a_ == a_); + EXPECT_FALSE(a_ != a_); + + EXPECT_TRUE(a_ != b_); + EXPECT_FALSE(a_ == b_); +} + +TEST(MakeTupleTest, WorksForScalarTypes) { + tuple a; + a = make_tuple(true, 5); + EXPECT_TRUE(get<0>(a)); + EXPECT_EQ(5, get<1>(a)); + + tuple b; + b = make_tuple('a', 'b', 5); + EXPECT_EQ('a', get<0>(b)); + EXPECT_EQ('b', get<1>(b)); + EXPECT_EQ(5, get<2>(b)); +} + +TEST(MakeTupleTest, WorksForPointers) { + int a[] = { 1, 2, 3, 4 }; + const char* const str = "hi"; + int* const p = a; + + tuple t; + t = make_tuple(str, p); + EXPECT_EQ(str, get<0>(t)); + EXPECT_EQ(p, get<1>(t)); +} + +} // namespace diff --git a/googletest/test/gtest-message_test.cc b/googletest/test/gtest-message_test.cc deleted file mode 100644 index 175238e..0000000 --- a/googletest/test/gtest-message_test.cc +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) -// -// Tests for the Message class. - -#include "gtest/gtest-message.h" - -#include "gtest/gtest.h" - -namespace { - -using ::testing::Message; - -// Tests the testing::Message class - -// Tests the default constructor. -TEST(MessageTest, DefaultConstructor) { - const Message msg; - EXPECT_EQ("", msg.GetString()); -} - -// Tests the copy constructor. -TEST(MessageTest, CopyConstructor) { - const Message msg1("Hello"); - const Message msg2(msg1); - EXPECT_EQ("Hello", msg2.GetString()); -} - -// Tests constructing a Message from a C-string. -TEST(MessageTest, ConstructsFromCString) { - Message msg("Hello"); - EXPECT_EQ("Hello", msg.GetString()); -} - -// Tests streaming a float. -TEST(MessageTest, StreamsFloat) { - const std::string s = (Message() << 1.23456F << " " << 2.34567F).GetString(); - // Both numbers should be printed with enough precision. - EXPECT_PRED_FORMAT2(testing::IsSubstring, "1.234560", s.c_str()); - EXPECT_PRED_FORMAT2(testing::IsSubstring, " 2.345669", s.c_str()); -} - -// Tests streaming a double. -TEST(MessageTest, StreamsDouble) { - const std::string s = (Message() << 1260570880.4555497 << " " - << 1260572265.1954534).GetString(); - // Both numbers should be printed with enough precision. - EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str()); - EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str()); -} - -// Tests streaming a non-char pointer. -TEST(MessageTest, StreamsPointer) { - int n = 0; - int* p = &n; - EXPECT_NE("(null)", (Message() << p).GetString()); -} - -// Tests streaming a NULL non-char pointer. -TEST(MessageTest, StreamsNullPointer) { - int* p = NULL; - EXPECT_EQ("(null)", (Message() << p).GetString()); -} - -// Tests streaming a C string. -TEST(MessageTest, StreamsCString) { - EXPECT_EQ("Foo", (Message() << "Foo").GetString()); -} - -// Tests streaming a NULL C string. -TEST(MessageTest, StreamsNullCString) { - char* p = NULL; - EXPECT_EQ("(null)", (Message() << p).GetString()); -} - -// Tests streaming std::string. -TEST(MessageTest, StreamsString) { - const ::std::string str("Hello"); - EXPECT_EQ("Hello", (Message() << str).GetString()); -} - -// Tests that we can output strings containing embedded NULs. -TEST(MessageTest, StreamsStringWithEmbeddedNUL) { - const char char_array_with_nul[] = - "Here's a NUL\0 and some more string"; - const ::std::string string_with_nul(char_array_with_nul, - sizeof(char_array_with_nul) - 1); - EXPECT_EQ("Here's a NUL\\0 and some more string", - (Message() << string_with_nul).GetString()); -} - -// Tests streaming a NUL char. -TEST(MessageTest, StreamsNULChar) { - EXPECT_EQ("\\0", (Message() << '\0').GetString()); -} - -// Tests streaming int. -TEST(MessageTest, StreamsInt) { - EXPECT_EQ("123", (Message() << 123).GetString()); -} - -// Tests that basic IO manipulators (endl, ends, and flush) can be -// streamed to Message. -TEST(MessageTest, StreamsBasicIoManip) { - EXPECT_EQ("Line 1.\nA NUL char \\0 in line 2.", - (Message() << "Line 1." << std::endl - << "A NUL char " << std::ends << std::flush - << " in line 2.").GetString()); -} - -// Tests Message::GetString() -TEST(MessageTest, GetString) { - Message msg; - msg << 1 << " lamb"; - EXPECT_EQ("1 lamb", msg.GetString()); -} - -// Tests streaming a Message object to an ostream. -TEST(MessageTest, StreamsToOStream) { - Message msg("Hello"); - ::std::stringstream ss; - ss << msg; - EXPECT_EQ("Hello", testing::internal::StringStreamToString(&ss)); -} - -// Tests that a Message object doesn't take up too much stack space. -TEST(MessageTest, DoesNotTakeUpMuchStackSpace) { - EXPECT_LE(sizeof(Message), 16U); -} - -} // namespace diff --git a/googletest/test/gtest-options_test.cc b/googletest/test/gtest-options_test.cc deleted file mode 100644 index 10cb1df..0000000 --- a/googletest/test/gtest-options_test.cc +++ /dev/null @@ -1,213 +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. -// -// -// Google Test UnitTestOptions tests -// -// This file tests classes and functions used internally by -// Google Test. They are subject to change without notice. -// -// This file is #included from gtest.cc, to avoid changing build or -// make-files on Windows and other platforms. Do not #include this file -// anywhere else! - -#include "gtest/gtest.h" - -#if GTEST_OS_WINDOWS_MOBILE -# include -#elif GTEST_OS_WINDOWS -# include -#endif // GTEST_OS_WINDOWS_MOBILE - -#include "src/gtest-internal-inl.h" - -namespace testing { -namespace internal { -namespace { - -// Turns the given relative path into an absolute path. -FilePath GetAbsolutePathOf(const FilePath& relative_path) { - return FilePath::ConcatPaths(FilePath::GetCurrentDir(), relative_path); -} - -// Testing UnitTestOptions::GetOutputFormat/GetOutputFile. - -TEST(XmlOutputTest, GetOutputFormatDefault) { - GTEST_FLAG(output) = ""; - EXPECT_STREQ("", UnitTestOptions::GetOutputFormat().c_str()); -} - -TEST(XmlOutputTest, GetOutputFormat) { - GTEST_FLAG(output) = "xml:filename"; - EXPECT_STREQ("xml", UnitTestOptions::GetOutputFormat().c_str()); -} - -TEST(XmlOutputTest, GetOutputFileDefault) { - GTEST_FLAG(output) = ""; - EXPECT_EQ(GetAbsolutePathOf(FilePath("test_detail.xml")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -} - -TEST(XmlOutputTest, GetOutputFileSingleFile) { - GTEST_FLAG(output) = "xml:filename.abc"; - EXPECT_EQ(GetAbsolutePathOf(FilePath("filename.abc")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -} - -TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) { - GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_; - const std::string expected_output_file = - GetAbsolutePathOf( - FilePath(std::string("path") + GTEST_PATH_SEP_ + - GetCurrentExecutableName().string() + ".xml")).string(); - const std::string& output_file = - UnitTestOptions::GetAbsolutePathToOutputFile(); -#if GTEST_OS_WINDOWS - EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); -#else - EXPECT_EQ(expected_output_file, output_file.c_str()); -#endif -} - -TEST(OutputFileHelpersTest, GetCurrentExecutableName) { - const std::string exe_str = GetCurrentExecutableName().string(); -#if GTEST_OS_WINDOWS - const bool success = - _strcmpi("gtest-options_test", exe_str.c_str()) == 0 || - _strcmpi("gtest-options-ex_test", exe_str.c_str()) == 0 || - _strcmpi("gtest_all_test", exe_str.c_str()) == 0 || - _strcmpi("gtest_dll_test", exe_str.c_str()) == 0; -#elif GTEST_OS_FUCHSIA - const bool success = exe_str == "app"; -#else - // TODO(wan@google.com): remove the hard-coded "lt-" prefix when - // Chandler Carruth's libtool replacement is ready. - const bool success = - exe_str == "gtest-options_test" || - exe_str == "gtest_all_test" || - exe_str == "lt-gtest_all_test" || - exe_str == "gtest_dll_test"; -#endif // GTEST_OS_WINDOWS - if (!success) - FAIL() << "GetCurrentExecutableName() returns " << exe_str; -} - -#if !GTEST_OS_FUCHSIA - -class XmlOutputChangeDirTest : public Test { - protected: - virtual void SetUp() { - original_working_dir_ = FilePath::GetCurrentDir(); - posix::ChDir(".."); - // This will make the test fail if run from the root directory. - EXPECT_NE(original_working_dir_.string(), - FilePath::GetCurrentDir().string()); - } - - virtual void TearDown() { - posix::ChDir(original_working_dir_.string().c_str()); - } - - FilePath original_working_dir_; -}; - -TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) { - GTEST_FLAG(output) = ""; - EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, - FilePath("test_detail.xml")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -} - -TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) { - GTEST_FLAG(output) = "xml"; - EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, - FilePath("test_detail.xml")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -} - -TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) { - GTEST_FLAG(output) = "xml:filename.abc"; - EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, - FilePath("filename.abc")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -} - -TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { - GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_; - const std::string expected_output_file = - FilePath::ConcatPaths( - original_working_dir_, - FilePath(std::string("path") + GTEST_PATH_SEP_ + - GetCurrentExecutableName().string() + ".xml")).string(); - const std::string& output_file = - UnitTestOptions::GetAbsolutePathToOutputFile(); -#if GTEST_OS_WINDOWS - EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); -#else - EXPECT_EQ(expected_output_file, output_file.c_str()); -#endif -} - -TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) { -#if GTEST_OS_WINDOWS - GTEST_FLAG(output) = "xml:c:\\tmp\\filename.abc"; - EXPECT_EQ(FilePath("c:\\tmp\\filename.abc").string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -#else - GTEST_FLAG(output) ="xml:/tmp/filename.abc"; - EXPECT_EQ(FilePath("/tmp/filename.abc").string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -#endif -} - -TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) { -#if GTEST_OS_WINDOWS - const std::string path = "c:\\tmp\\"; -#else - const std::string path = "/tmp/"; -#endif - - GTEST_FLAG(output) = "xml:" + path; - const std::string expected_output_file = - path + GetCurrentExecutableName().string() + ".xml"; - const std::string& output_file = - UnitTestOptions::GetAbsolutePathToOutputFile(); - -#if GTEST_OS_WINDOWS - EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); -#else - EXPECT_EQ(expected_output_file, output_file.c_str()); -#endif -} - -#endif // !GTEST_OS_FUCHSIA - -} // namespace -} // namespace internal -} // namespace testing diff --git a/googletest/test/gtest-port_test.cc b/googletest/test/gtest-port_test.cc deleted file mode 100644 index 3801e5e..0000000 --- a/googletest/test/gtest-port_test.cc +++ /dev/null @@ -1,1303 +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. -// -// Authors: vladl@google.com (Vlad Losev), wan@google.com (Zhanyong Wan) -// -// This file tests the internal cross-platform support utilities. - -#include "gtest/internal/gtest-port.h" - -#include - -#if GTEST_OS_MAC -# include -#endif // GTEST_OS_MAC - -#include -#include // For std::pair and std::make_pair. -#include - -#include "gtest/gtest.h" -#include "gtest/gtest-spi.h" -#include "src/gtest-internal-inl.h" - -using std::make_pair; -using std::pair; - -namespace testing { -namespace internal { - -TEST(IsXDigitTest, WorksForNarrowAscii) { - EXPECT_TRUE(IsXDigit('0')); - EXPECT_TRUE(IsXDigit('9')); - EXPECT_TRUE(IsXDigit('A')); - EXPECT_TRUE(IsXDigit('F')); - EXPECT_TRUE(IsXDigit('a')); - EXPECT_TRUE(IsXDigit('f')); - - EXPECT_FALSE(IsXDigit('-')); - EXPECT_FALSE(IsXDigit('g')); - EXPECT_FALSE(IsXDigit('G')); -} - -TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) { - EXPECT_FALSE(IsXDigit(static_cast('\x80'))); - EXPECT_FALSE(IsXDigit(static_cast('0' | '\x80'))); -} - -TEST(IsXDigitTest, WorksForWideAscii) { - EXPECT_TRUE(IsXDigit(L'0')); - EXPECT_TRUE(IsXDigit(L'9')); - EXPECT_TRUE(IsXDigit(L'A')); - EXPECT_TRUE(IsXDigit(L'F')); - EXPECT_TRUE(IsXDigit(L'a')); - EXPECT_TRUE(IsXDigit(L'f')); - - EXPECT_FALSE(IsXDigit(L'-')); - EXPECT_FALSE(IsXDigit(L'g')); - EXPECT_FALSE(IsXDigit(L'G')); -} - -TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) { - EXPECT_FALSE(IsXDigit(static_cast(0x80))); - EXPECT_FALSE(IsXDigit(static_cast(L'0' | 0x80))); - EXPECT_FALSE(IsXDigit(static_cast(L'0' | 0x100))); -} - -class Base { - public: - // Copy constructor and assignment operator do exactly what we need, so we - // use them. - Base() : member_(0) {} - explicit Base(int n) : member_(n) {} - virtual ~Base() {} - int member() { return member_; } - - private: - int member_; -}; - -class Derived : public Base { - public: - explicit Derived(int n) : Base(n) {} -}; - -TEST(ImplicitCastTest, ConvertsPointers) { - Derived derived(0); - EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_(&derived)); -} - -TEST(ImplicitCastTest, CanUseInheritance) { - Derived derived(1); - Base base = ::testing::internal::ImplicitCast_(derived); - EXPECT_EQ(derived.member(), base.member()); -} - -class Castable { - public: - explicit Castable(bool* converted) : converted_(converted) {} - operator Base() { - *converted_ = true; - return Base(); - } - - private: - bool* converted_; -}; - -TEST(ImplicitCastTest, CanUseNonConstCastOperator) { - bool converted = false; - Castable castable(&converted); - Base base = ::testing::internal::ImplicitCast_(castable); - EXPECT_TRUE(converted); -} - -class ConstCastable { - public: - explicit ConstCastable(bool* converted) : converted_(converted) {} - operator Base() const { - *converted_ = true; - return Base(); - } - - private: - bool* converted_; -}; - -TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) { - bool converted = false; - const ConstCastable const_castable(&converted); - Base base = ::testing::internal::ImplicitCast_(const_castable); - EXPECT_TRUE(converted); -} - -class ConstAndNonConstCastable { - public: - ConstAndNonConstCastable(bool* converted, bool* const_converted) - : converted_(converted), const_converted_(const_converted) {} - operator Base() { - *converted_ = true; - return Base(); - } - operator Base() const { - *const_converted_ = true; - return Base(); - } - - private: - bool* converted_; - bool* const_converted_; -}; - -TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) { - bool converted = false; - bool const_converted = false; - ConstAndNonConstCastable castable(&converted, &const_converted); - Base base = ::testing::internal::ImplicitCast_(castable); - EXPECT_TRUE(converted); - EXPECT_FALSE(const_converted); - - converted = false; - const_converted = false; - const ConstAndNonConstCastable const_castable(&converted, &const_converted); - base = ::testing::internal::ImplicitCast_(const_castable); - EXPECT_FALSE(converted); - EXPECT_TRUE(const_converted); -} - -class To { - public: - To(bool* converted) { *converted = true; } // NOLINT -}; - -TEST(ImplicitCastTest, CanUseImplicitConstructor) { - bool converted = false; - To to = ::testing::internal::ImplicitCast_(&converted); - (void)to; - EXPECT_TRUE(converted); -} - -TEST(IteratorTraitsTest, WorksForSTLContainerIterators) { - StaticAssertTypeEq::const_iterator>::value_type>(); - StaticAssertTypeEq::iterator>::value_type>(); -} - -TEST(IteratorTraitsTest, WorksForPointerToNonConst) { - StaticAssertTypeEq::value_type>(); - StaticAssertTypeEq::value_type>(); -} - -TEST(IteratorTraitsTest, WorksForPointerToConst) { - StaticAssertTypeEq::value_type>(); - StaticAssertTypeEq::value_type>(); -} - -// Tests that the element_type typedef is available in scoped_ptr and refers -// to the parameter type. -TEST(ScopedPtrTest, DefinesElementType) { - StaticAssertTypeEq::element_type>(); -} - -// TODO(vladl@google.com): Implement THE REST of scoped_ptr tests. - -TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) { - if (AlwaysFalse()) - GTEST_CHECK_(false) << "This should never be executed; " - "It's a compilation test only."; - - if (AlwaysTrue()) - GTEST_CHECK_(true); - else - ; // NOLINT - - if (AlwaysFalse()) - ; // NOLINT - else - GTEST_CHECK_(true) << ""; -} - -TEST(GtestCheckSyntaxTest, WorksWithSwitch) { - switch (0) { - case 1: - break; - default: - GTEST_CHECK_(true); - } - - switch (0) - case 0: - GTEST_CHECK_(true) << "Check failed in switch case"; -} - -// Verifies behavior of FormatFileLocation. -TEST(FormatFileLocationTest, FormatsFileLocation) { - EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42)); - EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42)); -} - -TEST(FormatFileLocationTest, FormatsUnknownFile) { - EXPECT_PRED_FORMAT2( - IsSubstring, "unknown file", FormatFileLocation(NULL, 42)); - EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(NULL, 42)); -} - -TEST(FormatFileLocationTest, FormatsUknownLine) { - EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1)); -} - -TEST(FormatFileLocationTest, FormatsUknownFileAndLine) { - EXPECT_EQ("unknown file:", FormatFileLocation(NULL, -1)); -} - -// Verifies behavior of FormatCompilerIndependentFileLocation. -TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) { - EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42)); -} - -TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) { - EXPECT_EQ("unknown file:42", - FormatCompilerIndependentFileLocation(NULL, 42)); -} - -TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) { - EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1)); -} - -TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) { - EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1)); -} - -#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA -void* ThreadFunc(void* data) { - internal::Mutex* mutex = static_cast(data); - mutex->Lock(); - mutex->Unlock(); - return NULL; -} - -TEST(GetThreadCountTest, ReturnsCorrectValue) { - const size_t starting_count = GetThreadCount(); - pthread_t thread_id; - - internal::Mutex mutex; - { - internal::MutexLock lock(&mutex); - pthread_attr_t attr; - ASSERT_EQ(0, pthread_attr_init(&attr)); - ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); - - const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex); - ASSERT_EQ(0, pthread_attr_destroy(&attr)); - ASSERT_EQ(0, status); - EXPECT_EQ(starting_count + 1, GetThreadCount()); - } - - void* dummy; - ASSERT_EQ(0, pthread_join(thread_id, &dummy)); - - // The OS may not immediately report the updated thread count after - // joining a thread, causing flakiness in this test. To counter that, we - // wait for up to .5 seconds for the OS to report the correct value. - for (int i = 0; i < 5; ++i) { - if (GetThreadCount() == starting_count) - break; - - SleepMilliseconds(100); - } - - EXPECT_EQ(starting_count, GetThreadCount()); -} -#else -TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) { - EXPECT_EQ(0U, GetThreadCount()); -} -#endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA - -TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { - const bool a_false_condition = false; - const char regex[] = -#ifdef _MSC_VER - "gtest-port_test\\.cc\\(\\d+\\):" -#elif GTEST_USES_POSIX_RE - "gtest-port_test\\.cc:[0-9]+" -#else - "gtest-port_test\\.cc:\\d+" -#endif // _MSC_VER - ".*a_false_condition.*Extra info.*"; - - EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info", - regex); -} - -#if GTEST_HAS_DEATH_TEST - -TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { - EXPECT_EXIT({ - GTEST_CHECK_(true) << "Extra info"; - ::std::cerr << "Success\n"; - exit(0); }, - ::testing::ExitedWithCode(0), "Success"); -} - -#endif // GTEST_HAS_DEATH_TEST - -// Verifies that Google Test choose regular expression engine appropriate to -// the platform. The test will produce compiler errors in case of failure. -// For simplicity, we only cover the most important platforms here. -TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) { -#if !GTEST_USES_PCRE -# if GTEST_HAS_POSIX_RE - - EXPECT_TRUE(GTEST_USES_POSIX_RE); - -# else - - EXPECT_TRUE(GTEST_USES_SIMPLE_RE); - -# endif -#endif // !GTEST_USES_PCRE -} - -#if GTEST_USES_POSIX_RE - -# if GTEST_HAS_TYPED_TEST - -template -class RETest : public ::testing::Test {}; - -// Defines StringTypes as the list of all string types that class RE -// supports. -typedef testing::Types< - ::std::string, -# if GTEST_HAS_GLOBAL_STRING - ::string, -# endif // GTEST_HAS_GLOBAL_STRING - const char*> StringTypes; - -TYPED_TEST_CASE(RETest, StringTypes); - -// Tests RE's implicit constructors. -TYPED_TEST(RETest, ImplicitConstructorWorks) { - const RE empty(TypeParam("")); - EXPECT_STREQ("", empty.pattern()); - - const RE simple(TypeParam("hello")); - EXPECT_STREQ("hello", simple.pattern()); - - const RE normal(TypeParam(".*(\\w+)")); - EXPECT_STREQ(".*(\\w+)", normal.pattern()); -} - -// Tests that RE's constructors reject invalid regular expressions. -TYPED_TEST(RETest, RejectsInvalidRegex) { - EXPECT_NONFATAL_FAILURE({ - const RE invalid(TypeParam("?")); - }, "\"?\" is not a valid POSIX Extended regular expression."); -} - -// Tests RE::FullMatch(). -TYPED_TEST(RETest, FullMatchWorks) { - const RE empty(TypeParam("")); - EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty)); - EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty)); - - const RE re(TypeParam("a.*z")); - EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re)); - EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re)); - EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re)); - EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re)); -} - -// Tests RE::PartialMatch(). -TYPED_TEST(RETest, PartialMatchWorks) { - const RE empty(TypeParam("")); - EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty)); - EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty)); - - const RE re(TypeParam("a.*z")); - EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re)); - EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re)); - EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re)); - EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re)); - EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re)); -} - -# endif // GTEST_HAS_TYPED_TEST - -#elif GTEST_USES_SIMPLE_RE - -TEST(IsInSetTest, NulCharIsNotInAnySet) { - EXPECT_FALSE(IsInSet('\0', "")); - EXPECT_FALSE(IsInSet('\0', "\0")); - EXPECT_FALSE(IsInSet('\0', "a")); -} - -TEST(IsInSetTest, WorksForNonNulChars) { - EXPECT_FALSE(IsInSet('a', "Ab")); - EXPECT_FALSE(IsInSet('c', "")); - - EXPECT_TRUE(IsInSet('b', "bcd")); - EXPECT_TRUE(IsInSet('b', "ab")); -} - -TEST(IsAsciiDigitTest, IsFalseForNonDigit) { - EXPECT_FALSE(IsAsciiDigit('\0')); - EXPECT_FALSE(IsAsciiDigit(' ')); - EXPECT_FALSE(IsAsciiDigit('+')); - EXPECT_FALSE(IsAsciiDigit('-')); - EXPECT_FALSE(IsAsciiDigit('.')); - EXPECT_FALSE(IsAsciiDigit('a')); -} - -TEST(IsAsciiDigitTest, IsTrueForDigit) { - EXPECT_TRUE(IsAsciiDigit('0')); - EXPECT_TRUE(IsAsciiDigit('1')); - EXPECT_TRUE(IsAsciiDigit('5')); - EXPECT_TRUE(IsAsciiDigit('9')); -} - -TEST(IsAsciiPunctTest, IsFalseForNonPunct) { - EXPECT_FALSE(IsAsciiPunct('\0')); - EXPECT_FALSE(IsAsciiPunct(' ')); - EXPECT_FALSE(IsAsciiPunct('\n')); - EXPECT_FALSE(IsAsciiPunct('a')); - EXPECT_FALSE(IsAsciiPunct('0')); -} - -TEST(IsAsciiPunctTest, IsTrueForPunct) { - for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) { - EXPECT_PRED1(IsAsciiPunct, *p); - } -} - -TEST(IsRepeatTest, IsFalseForNonRepeatChar) { - EXPECT_FALSE(IsRepeat('\0')); - EXPECT_FALSE(IsRepeat(' ')); - EXPECT_FALSE(IsRepeat('a')); - EXPECT_FALSE(IsRepeat('1')); - EXPECT_FALSE(IsRepeat('-')); -} - -TEST(IsRepeatTest, IsTrueForRepeatChar) { - EXPECT_TRUE(IsRepeat('?')); - EXPECT_TRUE(IsRepeat('*')); - EXPECT_TRUE(IsRepeat('+')); -} - -TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) { - EXPECT_FALSE(IsAsciiWhiteSpace('\0')); - EXPECT_FALSE(IsAsciiWhiteSpace('a')); - EXPECT_FALSE(IsAsciiWhiteSpace('1')); - EXPECT_FALSE(IsAsciiWhiteSpace('+')); - EXPECT_FALSE(IsAsciiWhiteSpace('_')); -} - -TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) { - EXPECT_TRUE(IsAsciiWhiteSpace(' ')); - EXPECT_TRUE(IsAsciiWhiteSpace('\n')); - EXPECT_TRUE(IsAsciiWhiteSpace('\r')); - EXPECT_TRUE(IsAsciiWhiteSpace('\t')); - EXPECT_TRUE(IsAsciiWhiteSpace('\v')); - EXPECT_TRUE(IsAsciiWhiteSpace('\f')); -} - -TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) { - EXPECT_FALSE(IsAsciiWordChar('\0')); - EXPECT_FALSE(IsAsciiWordChar('+')); - EXPECT_FALSE(IsAsciiWordChar('.')); - EXPECT_FALSE(IsAsciiWordChar(' ')); - EXPECT_FALSE(IsAsciiWordChar('\n')); -} - -TEST(IsAsciiWordCharTest, IsTrueForLetter) { - EXPECT_TRUE(IsAsciiWordChar('a')); - EXPECT_TRUE(IsAsciiWordChar('b')); - EXPECT_TRUE(IsAsciiWordChar('A')); - EXPECT_TRUE(IsAsciiWordChar('Z')); -} - -TEST(IsAsciiWordCharTest, IsTrueForDigit) { - EXPECT_TRUE(IsAsciiWordChar('0')); - EXPECT_TRUE(IsAsciiWordChar('1')); - EXPECT_TRUE(IsAsciiWordChar('7')); - EXPECT_TRUE(IsAsciiWordChar('9')); -} - -TEST(IsAsciiWordCharTest, IsTrueForUnderscore) { - EXPECT_TRUE(IsAsciiWordChar('_')); -} - -TEST(IsValidEscapeTest, IsFalseForNonPrintable) { - EXPECT_FALSE(IsValidEscape('\0')); - EXPECT_FALSE(IsValidEscape('\007')); -} - -TEST(IsValidEscapeTest, IsFalseForDigit) { - EXPECT_FALSE(IsValidEscape('0')); - EXPECT_FALSE(IsValidEscape('9')); -} - -TEST(IsValidEscapeTest, IsFalseForWhiteSpace) { - EXPECT_FALSE(IsValidEscape(' ')); - EXPECT_FALSE(IsValidEscape('\n')); -} - -TEST(IsValidEscapeTest, IsFalseForSomeLetter) { - EXPECT_FALSE(IsValidEscape('a')); - EXPECT_FALSE(IsValidEscape('Z')); -} - -TEST(IsValidEscapeTest, IsTrueForPunct) { - EXPECT_TRUE(IsValidEscape('.')); - EXPECT_TRUE(IsValidEscape('-')); - EXPECT_TRUE(IsValidEscape('^')); - EXPECT_TRUE(IsValidEscape('$')); - EXPECT_TRUE(IsValidEscape('(')); - EXPECT_TRUE(IsValidEscape(']')); - EXPECT_TRUE(IsValidEscape('{')); - EXPECT_TRUE(IsValidEscape('|')); -} - -TEST(IsValidEscapeTest, IsTrueForSomeLetter) { - EXPECT_TRUE(IsValidEscape('d')); - EXPECT_TRUE(IsValidEscape('D')); - EXPECT_TRUE(IsValidEscape('s')); - EXPECT_TRUE(IsValidEscape('S')); - EXPECT_TRUE(IsValidEscape('w')); - EXPECT_TRUE(IsValidEscape('W')); -} - -TEST(AtomMatchesCharTest, EscapedPunct) { - EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, '\\', ' ')); - EXPECT_FALSE(AtomMatchesChar(true, '_', '.')); - EXPECT_FALSE(AtomMatchesChar(true, '.', 'a')); - - EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\')); - EXPECT_TRUE(AtomMatchesChar(true, '_', '_')); - EXPECT_TRUE(AtomMatchesChar(true, '+', '+')); - EXPECT_TRUE(AtomMatchesChar(true, '.', '.')); -} - -TEST(AtomMatchesCharTest, Escaped_d) { - EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a')); - EXPECT_FALSE(AtomMatchesChar(true, 'd', '.')); - - EXPECT_TRUE(AtomMatchesChar(true, 'd', '0')); - EXPECT_TRUE(AtomMatchesChar(true, 'd', '9')); -} - -TEST(AtomMatchesCharTest, Escaped_D) { - EXPECT_FALSE(AtomMatchesChar(true, 'D', '0')); - EXPECT_FALSE(AtomMatchesChar(true, 'D', '9')); - - EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0')); - EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a')); - EXPECT_TRUE(AtomMatchesChar(true, 'D', '-')); -} - -TEST(AtomMatchesCharTest, Escaped_s) { - EXPECT_FALSE(AtomMatchesChar(true, 's', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 's', 'a')); - EXPECT_FALSE(AtomMatchesChar(true, 's', '.')); - EXPECT_FALSE(AtomMatchesChar(true, 's', '9')); - - EXPECT_TRUE(AtomMatchesChar(true, 's', ' ')); - EXPECT_TRUE(AtomMatchesChar(true, 's', '\n')); - EXPECT_TRUE(AtomMatchesChar(true, 's', '\t')); -} - -TEST(AtomMatchesCharTest, Escaped_S) { - EXPECT_FALSE(AtomMatchesChar(true, 'S', ' ')); - EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r')); - - EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0')); - EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a')); - EXPECT_TRUE(AtomMatchesChar(true, 'S', '9')); -} - -TEST(AtomMatchesCharTest, Escaped_w) { - EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 'w', '+')); - EXPECT_FALSE(AtomMatchesChar(true, 'w', ' ')); - EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n')); - - EXPECT_TRUE(AtomMatchesChar(true, 'w', '0')); - EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b')); - EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C')); - EXPECT_TRUE(AtomMatchesChar(true, 'w', '_')); -} - -TEST(AtomMatchesCharTest, Escaped_W) { - EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A')); - EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b')); - EXPECT_FALSE(AtomMatchesChar(true, 'W', '9')); - EXPECT_FALSE(AtomMatchesChar(true, 'W', '_')); - - EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0')); - EXPECT_TRUE(AtomMatchesChar(true, 'W', '*')); - EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n')); -} - -TEST(AtomMatchesCharTest, EscapedWhiteSpace) { - EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n')); - EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r')); - EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a')); - EXPECT_FALSE(AtomMatchesChar(true, 't', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 't', 't')); - EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f')); - - EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f')); - EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n')); - EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r')); - EXPECT_TRUE(AtomMatchesChar(true, 't', '\t')); - EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v')); -} - -TEST(AtomMatchesCharTest, UnescapedDot) { - EXPECT_FALSE(AtomMatchesChar(false, '.', '\n')); - - EXPECT_TRUE(AtomMatchesChar(false, '.', '\0')); - EXPECT_TRUE(AtomMatchesChar(false, '.', '.')); - EXPECT_TRUE(AtomMatchesChar(false, '.', 'a')); - EXPECT_TRUE(AtomMatchesChar(false, '.', ' ')); -} - -TEST(AtomMatchesCharTest, UnescapedChar) { - EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0')); - EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b')); - EXPECT_FALSE(AtomMatchesChar(false, '$', 'a')); - - EXPECT_TRUE(AtomMatchesChar(false, '$', '$')); - EXPECT_TRUE(AtomMatchesChar(false, '5', '5')); - EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z')); -} - -TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) { - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)), - "NULL is not a valid simple regular expression"); - EXPECT_NONFATAL_FAILURE( - ASSERT_FALSE(ValidateRegex("a\\")), - "Syntax error at index 1 in simple regular expression \"a\\\": "); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")), - "'\\' cannot appear at the end"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")), - "'\\' cannot appear at the end"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")), - "invalid escape sequence \"\\h\""); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")), - "'^' can only appear at the beginning"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")), - "'^' can only appear at the beginning"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")), - "'$' can only appear at the end"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")), - "'$' can only appear at the end"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")), - "'(' is unsupported"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")), - "')' is unsupported"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")), - "'[' is unsupported"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")), - "'{' is unsupported"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")), - "'?' can only follow a repeatable token"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")), - "'*' can only follow a repeatable token"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")), - "'+' can only follow a repeatable token"); -} - -TEST(ValidateRegexTest, ReturnsTrueForValid) { - EXPECT_TRUE(ValidateRegex("")); - EXPECT_TRUE(ValidateRegex("a")); - EXPECT_TRUE(ValidateRegex(".*")); - EXPECT_TRUE(ValidateRegex("^a_+")); - EXPECT_TRUE(ValidateRegex("^a\\t\\&?")); - EXPECT_TRUE(ValidateRegex("09*$")); - EXPECT_TRUE(ValidateRegex("^Z$")); - EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}")); -} - -TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) { - EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba")); - // Repeating more than once. - EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab")); - - // Repeating zero times. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba")); - // Repeating once. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab")); - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##")); -} - -TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) { - EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab")); - - // Repeating zero times. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc")); - // Repeating once. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc")); - // Repeating more than once. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g")); -} - -TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) { - EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab")); - // Repeating zero times. - EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc")); - - // Repeating once. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc")); - // Repeating more than once. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g")); -} - -TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) { - EXPECT_TRUE(MatchRegexAtHead("", "")); - EXPECT_TRUE(MatchRegexAtHead("", "ab")); -} - -TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) { - EXPECT_FALSE(MatchRegexAtHead("$", "a")); - - EXPECT_TRUE(MatchRegexAtHead("$", "")); - EXPECT_TRUE(MatchRegexAtHead("a$", "a")); -} - -TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) { - EXPECT_FALSE(MatchRegexAtHead("\\w", "+")); - EXPECT_FALSE(MatchRegexAtHead("\\W", "ab")); - - EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab")); - EXPECT_TRUE(MatchRegexAtHead("\\d", "1a")); -} - -TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) { - EXPECT_FALSE(MatchRegexAtHead(".+a", "abc")); - EXPECT_FALSE(MatchRegexAtHead("a?b", "aab")); - - EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab")); - EXPECT_TRUE(MatchRegexAtHead("a?b", "b")); - EXPECT_TRUE(MatchRegexAtHead("a?b", "ab")); -} - -TEST(MatchRegexAtHeadTest, - WorksWhenRegexStartsWithRepetionOfEscapeSequence) { - EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc")); - EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b")); - - EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab")); - EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b")); - EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b")); - EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b")); -} - -TEST(MatchRegexAtHeadTest, MatchesSequentially) { - EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc")); - - EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc")); -} - -TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) { - EXPECT_FALSE(MatchRegexAnywhere("", NULL)); -} - -TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) { - EXPECT_FALSE(MatchRegexAnywhere("^a", "ba")); - EXPECT_FALSE(MatchRegexAnywhere("^$", "a")); - - EXPECT_TRUE(MatchRegexAnywhere("^a", "ab")); - EXPECT_TRUE(MatchRegexAnywhere("^", "ab")); - EXPECT_TRUE(MatchRegexAnywhere("^$", "")); -} - -TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) { - EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123")); - EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888")); -} - -TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) { - EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5")); - EXPECT_TRUE(MatchRegexAnywhere(".*=", "=")); - EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc")); -} - -TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) { - EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5")); - EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...=")); -} - -// Tests RE's implicit constructors. -TEST(RETest, ImplicitConstructorWorks) { - const RE empty(""); - EXPECT_STREQ("", empty.pattern()); - - const RE simple("hello"); - EXPECT_STREQ("hello", simple.pattern()); -} - -// Tests that RE's constructors reject invalid regular expressions. -TEST(RETest, RejectsInvalidRegex) { - EXPECT_NONFATAL_FAILURE({ - const RE normal(NULL); - }, "NULL is not a valid simple regular expression"); - - EXPECT_NONFATAL_FAILURE({ - const RE normal(".*(\\w+"); - }, "'(' is unsupported"); - - EXPECT_NONFATAL_FAILURE({ - const RE invalid("^?"); - }, "'?' can only follow a repeatable token"); -} - -// Tests RE::FullMatch(). -TEST(RETest, FullMatchWorks) { - const RE empty(""); - EXPECT_TRUE(RE::FullMatch("", empty)); - EXPECT_FALSE(RE::FullMatch("a", empty)); - - const RE re1("a"); - EXPECT_TRUE(RE::FullMatch("a", re1)); - - const RE re("a.*z"); - EXPECT_TRUE(RE::FullMatch("az", re)); - EXPECT_TRUE(RE::FullMatch("axyz", re)); - EXPECT_FALSE(RE::FullMatch("baz", re)); - EXPECT_FALSE(RE::FullMatch("azy", re)); -} - -// Tests RE::PartialMatch(). -TEST(RETest, PartialMatchWorks) { - const RE empty(""); - EXPECT_TRUE(RE::PartialMatch("", empty)); - EXPECT_TRUE(RE::PartialMatch("a", empty)); - - const RE re("a.*z"); - EXPECT_TRUE(RE::PartialMatch("az", re)); - EXPECT_TRUE(RE::PartialMatch("axyz", re)); - EXPECT_TRUE(RE::PartialMatch("baz", re)); - EXPECT_TRUE(RE::PartialMatch("azy", re)); - EXPECT_FALSE(RE::PartialMatch("zza", re)); -} - -#endif // GTEST_USES_POSIX_RE - -#if !GTEST_OS_WINDOWS_MOBILE - -TEST(CaptureTest, CapturesStdout) { - CaptureStdout(); - fprintf(stdout, "abc"); - EXPECT_STREQ("abc", GetCapturedStdout().c_str()); - - CaptureStdout(); - fprintf(stdout, "def%cghi", '\0'); - EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout())); -} - -TEST(CaptureTest, CapturesStderr) { - CaptureStderr(); - fprintf(stderr, "jkl"); - EXPECT_STREQ("jkl", GetCapturedStderr().c_str()); - - CaptureStderr(); - fprintf(stderr, "jkl%cmno", '\0'); - EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr())); -} - -// Tests that stdout and stderr capture don't interfere with each other. -TEST(CaptureTest, CapturesStdoutAndStderr) { - CaptureStdout(); - CaptureStderr(); - fprintf(stdout, "pqr"); - fprintf(stderr, "stu"); - EXPECT_STREQ("pqr", GetCapturedStdout().c_str()); - EXPECT_STREQ("stu", GetCapturedStderr().c_str()); -} - -TEST(CaptureDeathTest, CannotReenterStdoutCapture) { - CaptureStdout(); - EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(), - "Only one stdout capturer can exist at a time"); - GetCapturedStdout(); - - // We cannot test stderr capturing using death tests as they use it - // themselves. -} - -#endif // !GTEST_OS_WINDOWS_MOBILE - -TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) { - ThreadLocal t1; - EXPECT_EQ(0, t1.get()); - - ThreadLocal t2; - EXPECT_TRUE(t2.get() == NULL); -} - -TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) { - ThreadLocal t1(123); - EXPECT_EQ(123, t1.get()); - - int i = 0; - ThreadLocal t2(&i); - EXPECT_EQ(&i, t2.get()); -} - -class NoDefaultContructor { - public: - explicit NoDefaultContructor(const char*) {} - NoDefaultContructor(const NoDefaultContructor&) {} -}; - -TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) { - ThreadLocal bar(NoDefaultContructor("foo")); - bar.pointer(); -} - -TEST(ThreadLocalTest, GetAndPointerReturnSameValue) { - ThreadLocal thread_local_string; - - EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get())); - - // Verifies the condition still holds after calling set. - thread_local_string.set("foo"); - EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get())); -} - -TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) { - ThreadLocal thread_local_string; - const ThreadLocal& const_thread_local_string = - thread_local_string; - - EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer()); - - thread_local_string.set("foo"); - EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer()); -} - -#if GTEST_IS_THREADSAFE - -void AddTwo(int* param) { *param += 2; } - -TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) { - int i = 40; - ThreadWithParam thread(&AddTwo, &i, NULL); - thread.Join(); - EXPECT_EQ(42, i); -} - -TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) { - // AssertHeld() is flaky only in the presence of multiple threads accessing - // the lock. In this case, the test is robust. - EXPECT_DEATH_IF_SUPPORTED({ - Mutex m; - { MutexLock lock(&m); } - m.AssertHeld(); - }, - "thread .*hold"); -} - -TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) { - Mutex m; - MutexLock lock(&m); - m.AssertHeld(); -} - -class AtomicCounterWithMutex { - public: - explicit AtomicCounterWithMutex(Mutex* mutex) : - value_(0), mutex_(mutex), random_(42) {} - - void Increment() { - MutexLock lock(mutex_); - int temp = value_; - { - // We need to put up a memory barrier to prevent reads and writes to - // value_ rearranged with the call to SleepMilliseconds when observed - // from other threads. -#if GTEST_HAS_PTHREAD - // On POSIX, locking a mutex puts up a memory barrier. We cannot use - // Mutex and MutexLock here or rely on their memory barrier - // functionality as we are testing them here. - pthread_mutex_t memory_barrier_mutex; - GTEST_CHECK_POSIX_SUCCESS_( - pthread_mutex_init(&memory_barrier_mutex, NULL)); - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex)); - - SleepMilliseconds(random_.Generate(30)); - - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex)); - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex)); -#elif GTEST_OS_WINDOWS - // On Windows, performing an interlocked access puts up a memory barrier. - volatile LONG dummy = 0; - ::InterlockedIncrement(&dummy); - SleepMilliseconds(random_.Generate(30)); - ::InterlockedIncrement(&dummy); -#else -# error "Memory barrier not implemented on this platform." -#endif // GTEST_HAS_PTHREAD - } - value_ = temp + 1; - } - int value() const { return value_; } - - private: - volatile int value_; - Mutex* const mutex_; // Protects value_. - Random random_; -}; - -void CountingThreadFunc(pair param) { - for (int i = 0; i < param.second; ++i) - param.first->Increment(); -} - -// Tests that the mutex only lets one thread at a time to lock it. -TEST(MutexTest, OnlyOneThreadCanLockAtATime) { - Mutex mutex; - AtomicCounterWithMutex locked_counter(&mutex); - - typedef ThreadWithParam > ThreadType; - const int kCycleCount = 20; - const int kThreadCount = 7; - scoped_ptr counting_threads[kThreadCount]; - Notification threads_can_start; - // Creates and runs kThreadCount threads that increment locked_counter - // kCycleCount times each. - for (int i = 0; i < kThreadCount; ++i) { - counting_threads[i].reset(new ThreadType(&CountingThreadFunc, - make_pair(&locked_counter, - kCycleCount), - &threads_can_start)); - } - threads_can_start.Notify(); - for (int i = 0; i < kThreadCount; ++i) - counting_threads[i]->Join(); - - // If the mutex lets more than one thread to increment the counter at a - // time, they are likely to encounter a race condition and have some - // increments overwritten, resulting in the lower then expected counter - // value. - EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value()); -} - -template -void RunFromThread(void (func)(T), T param) { - ThreadWithParam thread(func, param, NULL); - thread.Join(); -} - -void RetrieveThreadLocalValue( - pair*, std::string*> param) { - *param.second = param.first->get(); -} - -TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) { - ThreadLocal thread_local_string("foo"); - EXPECT_STREQ("foo", thread_local_string.get().c_str()); - - thread_local_string.set("bar"); - EXPECT_STREQ("bar", thread_local_string.get().c_str()); - - std::string result; - RunFromThread(&RetrieveThreadLocalValue, - make_pair(&thread_local_string, &result)); - EXPECT_STREQ("foo", result.c_str()); -} - -// Keeps track of whether of destructors being called on instances of -// DestructorTracker. On Windows, waits for the destructor call reports. -class DestructorCall { - public: - DestructorCall() { - invoked_ = false; -#if GTEST_OS_WINDOWS - wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL)); - GTEST_CHECK_(wait_event_.Get() != NULL); -#endif - } - - bool CheckDestroyed() const { -#if GTEST_OS_WINDOWS - if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0) - return false; -#endif - return invoked_; - } - - void ReportDestroyed() { - invoked_ = true; -#if GTEST_OS_WINDOWS - ::SetEvent(wait_event_.Get()); -#endif - } - - static std::vector& List() { return *list_; } - - static void ResetList() { - for (size_t i = 0; i < list_->size(); ++i) { - delete list_->at(i); - } - list_->clear(); - } - - private: - bool invoked_; -#if GTEST_OS_WINDOWS - AutoHandle wait_event_; -#endif - static std::vector* const list_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall); -}; - -std::vector* const DestructorCall::list_ = - new std::vector; - -// DestructorTracker keeps track of whether its instances have been -// destroyed. -class DestructorTracker { - public: - DestructorTracker() : index_(GetNewIndex()) {} - DestructorTracker(const DestructorTracker& /* rhs */) - : index_(GetNewIndex()) {} - ~DestructorTracker() { - // We never access DestructorCall::List() concurrently, so we don't need - // to protect this access with a mutex. - DestructorCall::List()[index_]->ReportDestroyed(); - } - - private: - static size_t GetNewIndex() { - DestructorCall::List().push_back(new DestructorCall); - return DestructorCall::List().size() - 1; - } - const size_t index_; - - GTEST_DISALLOW_ASSIGN_(DestructorTracker); -}; - -typedef ThreadLocal* ThreadParam; - -void CallThreadLocalGet(ThreadParam thread_local_param) { - thread_local_param->get(); -} - -// Tests that when a ThreadLocal object dies in a thread, it destroys -// the managed object for that thread. -TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) { - DestructorCall::ResetList(); - - { - ThreadLocal thread_local_tracker; - ASSERT_EQ(0U, DestructorCall::List().size()); - - // This creates another DestructorTracker object for the main thread. - thread_local_tracker.get(); - ASSERT_EQ(1U, DestructorCall::List().size()); - ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed()); - } - - // Now thread_local_tracker has died. - ASSERT_EQ(1U, DestructorCall::List().size()); - EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); - - DestructorCall::ResetList(); -} - -// Tests that when a thread exits, the thread-local object for that -// thread is destroyed. -TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) { - DestructorCall::ResetList(); - - { - ThreadLocal thread_local_tracker; - ASSERT_EQ(0U, DestructorCall::List().size()); - - // This creates another DestructorTracker object in the new thread. - ThreadWithParam thread( - &CallThreadLocalGet, &thread_local_tracker, NULL); - thread.Join(); - - // The thread has exited, and we should have a DestroyedTracker - // instance created for it. But it may not have been destroyed yet. - ASSERT_EQ(1U, DestructorCall::List().size()); - } - - // The thread has exited and thread_local_tracker has died. - ASSERT_EQ(1U, DestructorCall::List().size()); - EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); - - DestructorCall::ResetList(); -} - -TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) { - ThreadLocal thread_local_string; - thread_local_string.set("Foo"); - EXPECT_STREQ("Foo", thread_local_string.get().c_str()); - - std::string result; - RunFromThread(&RetrieveThreadLocalValue, - make_pair(&thread_local_string, &result)); - EXPECT_TRUE(result.empty()); -} - -#endif // GTEST_IS_THREADSAFE - -#if GTEST_OS_WINDOWS -TEST(WindowsTypesTest, HANDLEIsVoidStar) { - StaticAssertTypeEq(); -} - -#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) -TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) { - StaticAssertTypeEq(); -} -#else -TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) { - StaticAssertTypeEq(); -} -#endif - -#endif // GTEST_OS_WINDOWS - -} // namespace internal -} // namespace testing diff --git a/googletest/test/gtest-printers_test.cc b/googletest/test/gtest-printers_test.cc deleted file mode 100644 index 49b3bd4..0000000 --- a/googletest/test/gtest-printers_test.cc +++ /dev/null @@ -1,1737 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) - -// Google Test - The Google C++ Testing and Mocking Framework -// -// This file tests the universal value printer. - -#include "gtest/gtest-printers.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "gtest/gtest.h" - -#if GTEST_HAS_UNORDERED_MAP_ -# include // NOLINT -#endif // GTEST_HAS_UNORDERED_MAP_ - -#if GTEST_HAS_UNORDERED_SET_ -# include // NOLINT -#endif // GTEST_HAS_UNORDERED_SET_ - -#if GTEST_HAS_STD_FORWARD_LIST_ -# include // NOLINT -#endif // GTEST_HAS_STD_FORWARD_LIST_ - -// 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 -class UnprintableTemplateInGlobal { - public: - UnprintableTemplateInGlobal() : value_() {} - private: - T value_; -}; - -// A user-defined streamable type in the global namespace. -class StreamableInGlobal { - public: - virtual ~StreamableInGlobal() {} -}; - -inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) { - os << "StreamableInGlobal"; -} - -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() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); } - double z() const { return z_; } - private: - char xy_[8]; - double z_; -}; - -// A user-defined printable type in a user-chosen namespace. -struct PrintableViaPrintTo { - PrintableViaPrintTo() : value() {} - int value; -}; - -void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) { - *os << "PrintableViaPrintTo: " << x.value; -} - -// A 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 -class PrintableViaPrintToTemplate { - public: - explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {} - - const T& value() const { return value_; } - private: - T value_; -}; - -template -void PrintTo(const PrintableViaPrintToTemplate& x, ::std::ostream* os) { - *os << "PrintableViaPrintToTemplate: " << x.value(); -} - -// A user-defined streamable class template in a user namespace. -template -class StreamableTemplateInFoo { - public: - StreamableTemplateInFoo() : value_() {} - - const T& value() const { return value_; } - private: - T value_; -}; - -template -inline ::std::ostream& operator<<(::std::ostream& os, - const StreamableTemplateInFoo& x) { - return os << "StreamableTemplateInFoo: " << x.value(); -} - -// A user-defined streamable but recursivly-defined container type in -// a user namespace, it mimics therefore std::filesystem::path or -// boost::filesystem::path. -class PathLike { - public: - struct iterator { - typedef PathLike value_type; - }; - - PathLike() {} - - iterator begin() const { return iterator(); } - iterator end() const { return iterator(); } - - friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) { - return os << "Streamable-PathLike"; - } -}; - -} // namespace foo - -namespace testing { -namespace gtest_printers_test { - -using ::std::deque; -using ::std::list; -using ::std::make_pair; -using ::std::map; -using ::std::multimap; -using ::std::multiset; -using ::std::pair; -using ::std::set; -using ::std::vector; -using ::testing::PrintToString; -using ::testing::internal::FormatForComparisonFailureMessage; -using ::testing::internal::ImplicitCast_; -using ::testing::internal::NativeArray; -using ::testing::internal::RE; -using ::testing::internal::RelationToSourceReference; -using ::testing::internal::Strings; -using ::testing::internal::UniversalPrint; -using ::testing::internal::UniversalPrinter; -using ::testing::internal::UniversalTersePrint; -#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ -using ::testing::internal::UniversalTersePrintTupleFieldsToStrings; -#endif - -// Prints a value to a string using the universal value printer. This -// is a helper for testing UniversalPrinter::Print() for various types. -template -std::string Print(const T& value) { - ::std::stringstream ss; - UniversalPrinter::Print(value, &ss); - return ss.str(); -} - -// Prints a value passed by reference to a string, using the universal -// value printer. This is a helper for testing -// UniversalPrinter::Print() for various types. -template -std::string PrintByRef(const T& value) { - ::std::stringstream ss; - UniversalPrinter::Print(value, &ss); - 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(0))); -} - -TEST(PrintEnumTest, EnumWithPrintTo) { - EXPECT_EQ("kEWPT1", Print(kEWPT1)); - EXPECT_EQ("invalid", Print(static_cast(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, 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, 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, 0xB)", Print('\v')); - EXPECT_EQ("'\\x7F' (127)", Print('\x7F')); - EXPECT_EQ("'\\xFF' (255)", Print('\xFF')); - EXPECT_EQ("' ' (32, 0x20)", Print(' ')); - EXPECT_EQ("'a' (97, 0x61)", Print('a')); -} - -// signed char. -TEST(PrintCharTest, SignedChar) { - EXPECT_EQ("'\\0'", Print(static_cast('\0'))); - EXPECT_EQ("'\\xCE' (-50)", - Print(static_cast(-50))); -} - -// unsigned char. -TEST(PrintCharTest, UnsignedChar) { - EXPECT_EQ("'\\0'", Print(static_cast('\0'))); - EXPECT_EQ("'b' (98, 0x62)", - Print(static_cast('b'))); -} - -// Tests printing other simple, built-in types. - -// bool. -TEST(PrintBuiltInTypeTest, Bool) { - EXPECT_EQ("false", Print(false)); - EXPECT_EQ("true", Print(true)); -} - -// wchar_t. -TEST(PrintBuiltInTypeTest, Wchar_t) { - EXPECT_EQ("L'\\0'", Print(L'\0')); - EXPECT_EQ("L'\\'' (39, 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, 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, 0xB)", Print(L'\v')); - EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F')); - EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF')); - EXPECT_EQ("L' ' (32, 0x20)", Print(L' ')); - EXPECT_EQ("L'a' (97, 0x61)", Print(L'a')); - EXPECT_EQ("L'\\x576' (1398)", Print(static_cast(0x576))); - EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast(0xC74D))); -} - -// Test that Int64 provides more storage than wchar_t. -TEST(PrintTypeSizeTest, Wchar_t) { - EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64)); -} - -// Various integer types. -TEST(PrintBuiltInTypeTest, Integer) { - EXPECT_EQ("'\\xFF' (255)", Print(static_cast(255))); // uint8 - EXPECT_EQ("'\\x80' (-128)", Print(static_cast(-128))); // int8 - EXPECT_EQ("65535", Print(USHRT_MAX)); // uint16 - EXPECT_EQ("-32768", Print(SHRT_MIN)); // int16 - EXPECT_EQ("4294967295", Print(UINT_MAX)); // uint32 - EXPECT_EQ("-2147483648", Print(INT_MIN)); // int32 - EXPECT_EQ("18446744073709551615", - Print(static_cast(-1))); // uint64 - EXPECT_EQ("-9223372036854775808", - Print(static_cast(1) << 63)); // int64 -} - -// Size types. -TEST(PrintBuiltInTypeTest, Size_t) { - EXPECT_EQ("1", Print(sizeof('a'))); // size_t. -#if !GTEST_OS_WINDOWS - // Windows has no ssize_t type. - EXPECT_EQ("-2", Print(static_cast(-2))); // ssize_t. -#endif // !GTEST_OS_WINDOWS -} - -// Floating-points. -TEST(PrintBuiltInTypeTest, FloatingPoints) { - EXPECT_EQ("1.5", Print(1.5f)); // float - EXPECT_EQ("-2.5", Print(-2.5)); // double -} - -// Since ::std::stringstream::operator<<(const void *) formats the pointer -// output differently with different compilers, we have to create the expected -// output first and use it as our expectation. -static std::string PrintPointer(const void* p) { - ::std::stringstream expected_result_stream; - expected_result_stream << p; - return expected_result_stream.str(); -} - -// Tests printing C strings. - -// const char*. -TEST(PrintCStringTest, Const) { - const char* p = "World"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p)); -} - -// char*. -TEST(PrintCStringTest, NonConst) { - char p[] = "Hi"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"", - Print(static_cast(p))); -} - -// NULL C string. -TEST(PrintCStringTest, Null) { - const char* p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests that C strings are escaped properly. -TEST(PrintCStringTest, EscapesProperly) { - const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f" - "\\n\\r\\t\\v\\x7F\\xFF a\"", - Print(p)); -} - -// MSVC compiler can be configured to define whar_t as a typedef -// of unsigned short. Defining an overload for const wchar_t* in that case -// would cause pointers to unsigned shorts be printed as wide strings, -// possibly accessing more memory than intended and causing invalid -// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when -// wchar_t is implemented as a native type. -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) - -// const wchar_t*. -TEST(PrintWideCStringTest, Const) { - const wchar_t* p = L"World"; - EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p)); -} - -// wchar_t*. -TEST(PrintWideCStringTest, NonConst) { - wchar_t p[] = L"Hi"; - EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"", - Print(static_cast(p))); -} - -// NULL wide C string. -TEST(PrintWideCStringTest, Null) { - const wchar_t* p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests that wide C strings are escaped properly. -TEST(PrintWideCStringTest, EscapesProperly) { - const wchar_t 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(static_cast(s))); -} -#endif // native wchar_t - -// Tests printing pointers to other char types. - -// signed char*. -TEST(PrintCharPointerTest, SignedChar) { - signed char* p = reinterpret_cast(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// const signed char*. -TEST(PrintCharPointerTest, ConstSignedChar) { - signed char* p = reinterpret_cast(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// unsigned char*. -TEST(PrintCharPointerTest, UnsignedChar) { - unsigned char* p = reinterpret_cast(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// const unsigned char*. -TEST(PrintCharPointerTest, ConstUnsignedChar) { - const unsigned char* p = reinterpret_cast(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing pointers to simple, built-in types. - -// bool*. -TEST(PrintPointerToBuiltInTypeTest, Bool) { - bool* p = reinterpret_cast(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// void*. -TEST(PrintPointerToBuiltInTypeTest, Void) { - void* p = reinterpret_cast(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// const void*. -TEST(PrintPointerToBuiltInTypeTest, ConstVoid) { - const void* p = reinterpret_cast(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing pointers to pointers. -TEST(PrintPointerToPointerTest, IntPointerPointer) { - int** p = reinterpret_cast(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing (non-member) function pointers. - -void MyFunction(int /* n */) {} - -TEST(PrintPointerTest, NonMemberFunctionPointer) { - // We cannot directly cast &MyFunction to const void* because the - // standard disallows casting between pointers to functions and - // pointers to objects, and some compilers (e.g. GCC 3.4) enforce - // this limitation. - EXPECT_EQ( - PrintPointer(reinterpret_cast( - reinterpret_cast(&MyFunction))), - Print(&MyFunction)); - int (*p)(bool) = NULL; // NOLINT - EXPECT_EQ("NULL", Print(p)); -} - -// An assertion predicate determining whether a one string is a prefix for -// another. -template -AssertionResult HasPrefix(const StringType& str, const StringType& prefix) { - if (str.find(prefix, 0) == 0) - return AssertionSuccess(); - - const bool is_wide_string = sizeof(prefix[0]) > 1; - const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; - return AssertionFailure() - << begin_string_quote << prefix << "\" is not a prefix of " - << begin_string_quote << str << "\"\n"; -} - -// Tests printing member variable pointers. Although they are called -// pointers, they don't point to a location in the address space. -// Their representation is implementation-defined. Thus they will be -// printed as raw bytes. - -struct Foo { - public: - virtual ~Foo() {} - int MyMethod(char x) { return x + 1; } - virtual char MyVirtualMethod(int /* n */) { return 'a'; } - - int value; -}; - -TEST(PrintPointerTest, MemberVariablePointer) { - EXPECT_TRUE(HasPrefix(Print(&Foo::value), - Print(sizeof(&Foo::value)) + "-byte object ")); - int (Foo::*p) = NULL; // NOLINT - EXPECT_TRUE(HasPrefix(Print(p), - Print(sizeof(p)) + "-byte object ")); -} - -// Tests printing member function pointers. Although they are called -// pointers, they don't point to a location in the address space. -// Their representation is implementation-defined. Thus they will be -// printed as raw bytes. -TEST(PrintPointerTest, MemberFunctionPointer) { - EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod), - Print(sizeof(&Foo::MyMethod)) + "-byte object ")); - EXPECT_TRUE( - HasPrefix(Print(&Foo::MyVirtualMethod), - Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object ")); - int (Foo::*p)(char) = NULL; // NOLINT - EXPECT_TRUE(HasPrefix(Print(p), - Print(sizeof(p)) + "-byte object ")); -} - -// Tests printing C arrays. - -// The difference between this and Print() is that it ensures that the -// argument is a reference to an array. -template -std::string PrintArrayHelper(T (&a)[N]) { - return Print(a); -} - -// One-dimensional array. -TEST(PrintArrayTest, OneDimensionalArray) { - int a[5] = { 1, 2, 3, 4, 5 }; - EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a)); -} - -// Two-dimensional array. -TEST(PrintArrayTest, TwoDimensionalArray) { - int a[2][5] = { - { 1, 2, 3, 4, 5 }, - { 6, 7, 8, 9, 0 } - }; - EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a)); -} - -// Array of const elements. -TEST(PrintArrayTest, ConstArray) { - const bool a[1] = { false }; - EXPECT_EQ("{ false }", PrintArrayHelper(a)); -} - -// char array without terminating NUL. -TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) { - // Array a contains '\0' in the middle and doesn't end with '\0'. - char a[] = { 'H', '\0', 'i' }; - EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a)); -} - -// const char array with terminating NUL. -TEST(PrintArrayTest, ConstCharArrayWithTerminatingNul) { - const char a[] = "\0Hi"; - EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a)); -} - -// const wchar_t array without terminating NUL. -TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) { - // Array a contains '\0' in the middle and doesn't end with '\0'. - const wchar_t a[] = { L'H', L'\0', L'i' }; - EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a)); -} - -// wchar_t array with terminating NUL. -TEST(PrintArrayTest, WConstCharArrayWithTerminatingNul) { - const wchar_t a[] = L"\0Hi"; - EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a)); -} - -// Array of objects. -TEST(PrintArrayTest, ObjectArray) { - std::string a[3] = {"Hi", "Hello", "Ni hao"}; - EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a)); -} - -// Array with many elements. -TEST(PrintArrayTest, BigArray) { - int a[100] = { 1, 2, 3 }; - EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }", - PrintArrayHelper(a)); -} - -// Tests printing ::string and ::std::string. - -#if GTEST_HAS_GLOBAL_STRING -// ::string. -TEST(PrintStringTest, StringInGlobalNamespace) { - const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; - const ::string str(s, sizeof(s)); - EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"", - Print(str)); -} -#endif // GTEST_HAS_GLOBAL_STRING - -// ::std::string. -TEST(PrintStringTest, StringInStdNamespace) { - const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; - const ::std::string str(s, sizeof(s)); - EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"", - Print(str)); -} - -TEST(PrintStringTest, StringAmbiguousHex) { - // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of: - // '\x6', '\x6B', or '\x6BA'. - - // a hex escaping sequence following by a decimal digit - EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3"))); - // a hex escaping sequence following by a hex digit (lower-case) - EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas"))); - // a hex escaping sequence following by a hex digit (upper-case) - EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA"))); - // a hex escaping sequence following by a non-xdigit - EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!"))); -} - -// Tests printing ::wstring and ::std::wstring. - -#if GTEST_HAS_GLOBAL_WSTRING -// ::wstring. -TEST(PrintWideStringTest, StringInGlobalNamespace) { - const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; - const ::wstring str(s, sizeof(s)/sizeof(wchar_t)); - EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" - "\\xD3\\x576\\x8D3\\xC74D a\\0\"", - Print(str)); -} -#endif // GTEST_HAS_GLOBAL_WSTRING - -#if GTEST_HAS_STD_WSTRING -// ::std::wstring. -TEST(PrintWideStringTest, StringInStdNamespace) { - const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; - const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t)); - EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" - "\\xD3\\x576\\x8D3\\xC74D a\\0\"", - Print(str)); -} - -TEST(PrintWideStringTest, StringAmbiguousHex) { - // same for wide strings. - EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3"))); - EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", - Print(::std::wstring(L"mm\x6" L"bananas"))); - EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", - Print(::std::wstring(L"NOM\x6" L"BANANA"))); - EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!"))); -} -#endif // GTEST_HAS_STD_WSTRING - -// Tests printing types that support generic streaming (i.e. streaming -// to std::basic_ostream for any valid Char and -// CharTraits types). - -// Tests printing a non-template type that supports generic streaming. - -class AllowsGenericStreaming {}; - -template -std::basic_ostream& operator<<( - std::basic_ostream& os, - const AllowsGenericStreaming& /* a */) { - return os << "AllowsGenericStreaming"; -} - -TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) { - AllowsGenericStreaming a; - EXPECT_EQ("AllowsGenericStreaming", Print(a)); -} - -// Tests printing a template type that supports generic streaming. - -template -class AllowsGenericStreamingTemplate {}; - -template -std::basic_ostream& operator<<( - std::basic_ostream& os, - const AllowsGenericStreamingTemplate& /* a */) { - return os << "AllowsGenericStreamingTemplate"; -} - -TEST(PrintTypeWithGenericStreamingTest, TemplateType) { - AllowsGenericStreamingTemplate a; - EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a)); -} - -// Tests printing a type that supports generic streaming and can be -// implicitly converted to another printable type. - -template -class AllowsGenericStreamingAndImplicitConversionTemplate { - public: - operator bool() const { return false; } -}; - -template -std::basic_ostream& operator<<( - std::basic_ostream& os, - const AllowsGenericStreamingAndImplicitConversionTemplate& /* a */) { - return os << "AllowsGenericStreamingAndImplicitConversionTemplate"; -} - -TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) { - AllowsGenericStreamingAndImplicitConversionTemplate a; - EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a)); -} - -#if GTEST_HAS_ABSL - -// Tests printing ::absl::string_view. - -TEST(PrintStringViewTest, SimpleStringView) { - const ::absl::string_view sp = "Hello"; - EXPECT_EQ("\"Hello\"", Print(sp)); -} - -TEST(PrintStringViewTest, UnprintableCharacters) { - const char str[] = "NUL (\0) and \r\t"; - const ::absl::string_view sp(str, sizeof(str) - 1); - EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp)); -} - -#endif // GTEST_HAS_ABSL - -// Tests printing STL containers. - -TEST(PrintStlContainerTest, EmptyDeque) { - deque empty; - EXPECT_EQ("{}", Print(empty)); -} - -TEST(PrintStlContainerTest, NonEmptyDeque) { - deque non_empty; - non_empty.push_back(1); - non_empty.push_back(3); - EXPECT_EQ("{ 1, 3 }", Print(non_empty)); -} - -#if GTEST_HAS_UNORDERED_MAP_ - -TEST(PrintStlContainerTest, OneElementHashMap) { - ::std::unordered_map map1; - map1[1] = 'a'; - EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1)); -} - -TEST(PrintStlContainerTest, HashMultiMap) { - ::std::unordered_multimap map1; - map1.insert(make_pair(5, true)); - map1.insert(make_pair(5, false)); - - // Elements of hash_multimap can be printed in any order. - const std::string result = Print(map1); - EXPECT_TRUE(result == "{ (5, true), (5, false) }" || - result == "{ (5, false), (5, true) }") - << " where Print(map1) returns \"" << result << "\"."; -} - -#endif // GTEST_HAS_UNORDERED_MAP_ - -#if GTEST_HAS_UNORDERED_SET_ - -TEST(PrintStlContainerTest, HashSet) { - ::std::unordered_set set1; - set1.insert(1); - EXPECT_EQ("{ 1 }", Print(set1)); -} - -TEST(PrintStlContainerTest, HashMultiSet) { - const int kSize = 5; - int a[kSize] = { 1, 1, 2, 5, 1 }; - ::std::unordered_multiset set1(a, a + kSize); - - // Elements of hash_multiset can be printed in any order. - const std::string result = Print(set1); - const std::string expected_pattern = "{ d, d, d, d, d }"; // d means a digit. - - // Verifies the result matches the expected pattern; also extracts - // the numbers in the result. - ASSERT_EQ(expected_pattern.length(), result.length()); - std::vector numbers; - for (size_t i = 0; i != result.length(); i++) { - if (expected_pattern[i] == 'd') { - ASSERT_NE(isdigit(static_cast(result[i])), 0); - numbers.push_back(result[i] - '0'); - } else { - EXPECT_EQ(expected_pattern[i], result[i]) << " where result is " - << result; - } - } - - // Makes sure the result contains the right numbers. - std::sort(numbers.begin(), numbers.end()); - std::sort(a, a + kSize); - EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); -} - -#endif // GTEST_HAS_UNORDERED_SET_ - -TEST(PrintStlContainerTest, List) { - const std::string a[] = {"hello", "world"}; - const list strings(a, a + 2); - EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings)); -} - -TEST(PrintStlContainerTest, Map) { - map map1; - map1[1] = true; - map1[5] = false; - map1[3] = true; - EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1)); -} - -TEST(PrintStlContainerTest, MultiMap) { - multimap map1; - // The make_pair template function would deduce the type as - // pair here, and since the key part in a multimap has to - // be constant, without a templated ctor in the pair class (as in - // libCstd on Solaris), make_pair call would fail to compile as no - // implicit conversion is found. Thus explicit typename is used - // here instead. - map1.insert(pair(true, 0)); - map1.insert(pair(true, 1)); - map1.insert(pair(false, 2)); - EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1)); -} - -TEST(PrintStlContainerTest, Set) { - const unsigned int a[] = { 3, 0, 5 }; - set set1(a, a + 3); - EXPECT_EQ("{ 0, 3, 5 }", Print(set1)); -} - -TEST(PrintStlContainerTest, MultiSet) { - const int a[] = { 1, 1, 2, 5, 1 }; - multiset set1(a, a + 5); - EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1)); -} - -#if GTEST_HAS_STD_FORWARD_LIST_ -// is available on Linux in the google3 mode, but not on -// Windows or Mac OS X. - -TEST(PrintStlContainerTest, SinglyLinkedList) { - int a[] = { 9, 2, 8 }; - const std::forward_list ints(a, a + 3); - EXPECT_EQ("{ 9, 2, 8 }", Print(ints)); -} -#endif // GTEST_HAS_STD_FORWARD_LIST_ - -TEST(PrintStlContainerTest, Pair) { - pair p(true, 5); - EXPECT_EQ("(true, 5)", Print(p)); -} - -TEST(PrintStlContainerTest, Vector) { - vector v; - v.push_back(1); - v.push_back(2); - EXPECT_EQ("{ 1, 2 }", Print(v)); -} - -TEST(PrintStlContainerTest, LongSequence) { - const int a[100] = { 1, 2, 3 }; - const vector v(a, a + 100); - EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " - "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v)); -} - -TEST(PrintStlContainerTest, NestedContainer) { - const int a1[] = { 1, 2 }; - const int a2[] = { 3, 4, 5 }; - const list l1(a1, a1 + 2); - const list l2(a2, a2 + 3); - - vector > v; - v.push_back(l1); - v.push_back(l2); - EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v)); -} - -TEST(PrintStlContainerTest, OneDimensionalNativeArray) { - const int a[3] = { 1, 2, 3 }; - NativeArray b(a, 3, RelationToSourceReference()); - EXPECT_EQ("{ 1, 2, 3 }", Print(b)); -} - -TEST(PrintStlContainerTest, TwoDimensionalNativeArray) { - const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; - NativeArray b(a, 2, RelationToSourceReference()); - EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b)); -} - -// Tests that a class named iterator isn't treated as a container. - -struct iterator { - char x; -}; - -TEST(PrintStlContainerTest, Iterator) { - iterator it = {}; - EXPECT_EQ("1-byte object <00>", Print(it)); -} - -// Tests that a class named const_iterator isn't treated as a container. - -struct const_iterator { - char x; -}; - -TEST(PrintStlContainerTest, ConstIterator) { - const_iterator it = {}; - EXPECT_EQ("1-byte object <00>", Print(it)); -} - -#if GTEST_HAS_TR1_TUPLE -// Tests printing ::std::tr1::tuples. - -// Tuples of various arities. -TEST(PrintTr1TupleTest, VariousSizes) { - ::std::tr1::tuple<> t0; - EXPECT_EQ("()", Print(t0)); - - ::std::tr1::tuple t1(5); - EXPECT_EQ("(5)", Print(t1)); - - ::std::tr1::tuple t2('a', true); - EXPECT_EQ("('a' (97, 0x61), true)", Print(t2)); - - ::std::tr1::tuple t3(false, 2, 3); - EXPECT_EQ("(false, 2, 3)", Print(t3)); - - ::std::tr1::tuple t4(false, 2, 3, 4); - EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); - - ::std::tr1::tuple t5(false, 2, 3, 4, true); - EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5)); - - ::std::tr1::tuple t6(false, 2, 3, 4, true, 6); - EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6)); - - ::std::tr1::tuple t7( - false, 2, 3, 4, true, 6, 7); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7)); - - ::std::tr1::tuple t8( - false, 2, 3, 4, true, 6, 7, true); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8)); - - ::std::tr1::tuple t9( - false, 2, 3, 4, true, 6, 7, true, 9); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9)); - - const char* const str = "8"; - // VC++ 2010's implementation of tuple of C++0x is deficient, requiring - // an explicit type cast of NULL to be used. - ::std::tr1::tuple - t10(false, 'a', static_cast(3), 4, 5, 1.5F, -2.5, str, // NOLINT - ImplicitCast_(NULL), "10"); - EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + - " pointing to \"8\", NULL, \"10\")", - Print(t10)); -} - -// Nested tuples. -TEST(PrintTr1TupleTest, NestedTuple) { - ::std::tr1::tuple< ::std::tr1::tuple, char> nested( - ::std::tr1::make_tuple(5, true), 'a'); - EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); -} - -#endif // GTEST_HAS_TR1_TUPLE - -#if GTEST_HAS_STD_TUPLE_ -// Tests printing ::std::tuples. - -// Tuples of various arities. -TEST(PrintStdTupleTest, VariousSizes) { - ::std::tuple<> t0; - EXPECT_EQ("()", Print(t0)); - - ::std::tuple t1(5); - EXPECT_EQ("(5)", Print(t1)); - - ::std::tuple t2('a', true); - EXPECT_EQ("('a' (97, 0x61), true)", Print(t2)); - - ::std::tuple t3(false, 2, 3); - EXPECT_EQ("(false, 2, 3)", Print(t3)); - - ::std::tuple t4(false, 2, 3, 4); - EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); - - ::std::tuple t5(false, 2, 3, 4, true); - EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5)); - - ::std::tuple t6(false, 2, 3, 4, true, 6); - EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6)); - - ::std::tuple t7( - false, 2, 3, 4, true, 6, 7); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7)); - - ::std::tuple t8( - false, 2, 3, 4, true, 6, 7, true); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8)); - - ::std::tuple t9( - false, 2, 3, 4, true, 6, 7, true, 9); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9)); - - const char* const str = "8"; - // VC++ 2010's implementation of tuple of C++0x is deficient, requiring - // an explicit type cast of NULL to be used. - ::std::tuple - t10(false, 'a', static_cast(3), 4, 5, 1.5F, -2.5, str, // NOLINT - ImplicitCast_(NULL), "10"); - EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + - " pointing to \"8\", NULL, \"10\")", - Print(t10)); -} - -// Nested tuples. -TEST(PrintStdTupleTest, NestedTuple) { - ::std::tuple< ::std::tuple, char> nested( - ::std::make_tuple(5, true), 'a'); - EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); -} - -#endif // GTEST_LANG_CXX11 - -#if GTEST_LANG_CXX11 -TEST(PrintNullptrT, Basic) { - EXPECT_EQ("(nullptr)", Print(nullptr)); -} -#endif // GTEST_LANG_CXX11 - -// Tests printing user-defined unprintable types. - -// Unprintable types in the global namespace. -TEST(PrintUnprintableTypeTest, InGlobalNamespace) { - EXPECT_EQ("1-byte object <00>", - Print(UnprintableTemplateInGlobal())); -} - -// Unprintable types in a user namespace. -TEST(PrintUnprintableTypeTest, InUserNamespace) { - EXPECT_EQ("16-byte object ", - Print(::foo::UnprintableInFoo())); -} - -// Unprintable types are that too big to be printed completely. - -struct Big { - Big() { memset(array, 0, sizeof(array)); } - char array[257]; -}; - -TEST(PrintUnpritableTypeTest, BigObject) { - EXPECT_EQ("257-byte object <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())); -} - -// Tests printing user-defined streamable types. - -// Streamable types in the global namespace. -TEST(PrintStreamableTypeTest, InGlobalNamespace) { - StreamableInGlobal x; - EXPECT_EQ("StreamableInGlobal", Print(x)); - EXPECT_EQ("StreamableInGlobal*", Print(&x)); -} - -// Printable template types in a user namespace. -TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) { - EXPECT_EQ("StreamableTemplateInFoo: 0", - Print(::foo::StreamableTemplateInFoo())); -} - -// Tests printing a user-defined recursive container type that has a << -// operator. -TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) { - ::foo::PathLike x; - EXPECT_EQ("Streamable-PathLike", Print(x)); - const ::foo::PathLike cx; - EXPECT_EQ("Streamable-PathLike", Print(cx)); -} - -// Tests printing user-defined types that have a PrintTo() function. -TEST(PrintPrintableTypeTest, InUserNamespace) { - EXPECT_EQ("PrintableViaPrintTo: 0", - 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", - Print(::foo::PrintableViaPrintToTemplate(5))); -} - -// Tests that the universal printer prints both the address and the -// value of a reference. -TEST(PrintReferenceTest, PrintsAddressAndValue) { - int n = 5; - EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n)); - - int a[2][3] = { - { 0, 1, 2 }, - { 3, 4, 5 } - }; - EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }", - PrintByRef(a)); - - const ::foo::UnprintableInFoo x; - EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object " - "", - PrintByRef(x)); -} - -// Tests that the universal printer prints a function pointer passed by -// reference. -TEST(PrintReferenceTest, HandlesFunctionPointer) { - void (*fp)(int n) = &MyFunction; - const std::string fp_pointer_string = - PrintPointer(reinterpret_cast(&fp)); - // We cannot directly cast &MyFunction to const void* because the - // standard disallows casting between pointers to functions and - // pointers to objects, and some compilers (e.g. GCC 3.4) enforce - // this limitation. - const std::string fp_string = PrintPointer(reinterpret_cast( - reinterpret_cast(fp))); - EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, - PrintByRef(fp)); -} - -// Tests that the universal printer prints a member function pointer -// passed by reference. -TEST(PrintReferenceTest, HandlesMemberFunctionPointer) { - int (Foo::*p)(char ch) = &Foo::MyMethod; - EXPECT_TRUE(HasPrefix( - PrintByRef(p), - "@" + PrintPointer(reinterpret_cast(&p)) + " " + - Print(sizeof(p)) + "-byte object ")); - - char (Foo::*p2)(int n) = &Foo::MyVirtualMethod; - EXPECT_TRUE(HasPrefix( - PrintByRef(p2), - "@" + PrintPointer(reinterpret_cast(&p2)) + " " + - Print(sizeof(p2)) + "-byte object ")); -} - -// Tests that the universal printer prints a member variable pointer -// passed by reference. -TEST(PrintReferenceTest, HandlesMemberVariablePointer) { - int (Foo::*p) = &Foo::value; // NOLINT - EXPECT_TRUE(HasPrefix( - PrintByRef(p), - "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object ")); -} - -// Tests that FormatForComparisonFailureMessage(), which is used to print -// an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion -// fails, formats the operand in the desired way. - -// scalar -TEST(FormatForComparisonFailureMessageTest, WorksForScalar) { - EXPECT_STREQ("123", - FormatForComparisonFailureMessage(123, 124).c_str()); -} - -// non-char pointer -TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) { - int n = 0; - EXPECT_EQ(PrintPointer(&n), - FormatForComparisonFailureMessage(&n, &n).c_str()); -} - -// non-char array -TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) { - // In expression 'array == x', 'array' is compared by pointer. - // Therefore we want to print an array operand as a pointer. - int n[] = { 1, 2, 3 }; - EXPECT_EQ(PrintPointer(n), - FormatForComparisonFailureMessage(n, n).c_str()); -} - -// Tests formatting a char pointer when it's compared with another pointer. -// In this case we want to print it as a raw pointer, as the comparison is by -// pointer. - -// char pointer vs pointer -TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) { - // In expression 'p == x', where 'p' and 'x' are (const or not) char - // pointers, the operands are compared by pointer. Therefore we - // want to print 'p' as a pointer instead of a C string (we don't - // even know if it's supposed to point to a valid C string). - - // const char* - const char* s = "hello"; - EXPECT_EQ(PrintPointer(s), - FormatForComparisonFailureMessage(s, s).c_str()); - - // char* - char ch = 'a'; - EXPECT_EQ(PrintPointer(&ch), - FormatForComparisonFailureMessage(&ch, &ch).c_str()); -} - -// wchar_t pointer vs pointer -TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) { - // In expression 'p == x', where 'p' and 'x' are (const or not) char - // pointers, the operands are compared by pointer. Therefore we - // want to print 'p' as a pointer instead of a wide C string (we don't - // even know if it's supposed to point to a valid wide C string). - - // const wchar_t* - const wchar_t* s = L"hello"; - EXPECT_EQ(PrintPointer(s), - FormatForComparisonFailureMessage(s, s).c_str()); - - // wchar_t* - wchar_t ch = L'a'; - EXPECT_EQ(PrintPointer(&ch), - FormatForComparisonFailureMessage(&ch, &ch).c_str()); -} - -// Tests formatting a char pointer when it's compared to a string object. -// In this case we want to print the char pointer as a C string. - -#if GTEST_HAS_GLOBAL_STRING -// char pointer vs ::string -TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsString) { - const char* s = "hello \"world"; - EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped. - FormatForComparisonFailureMessage(s, ::string()).c_str()); - - // char* - char str[] = "hi\1"; - char* p = str; - EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped. - FormatForComparisonFailureMessage(p, ::string()).c_str()); -} -#endif - -// char pointer vs std::string -TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) { - const char* s = "hello \"world"; - EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped. - FormatForComparisonFailureMessage(s, ::std::string()).c_str()); - - // char* - char str[] = "hi\1"; - char* p = str; - EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped. - FormatForComparisonFailureMessage(p, ::std::string()).c_str()); -} - -#if GTEST_HAS_GLOBAL_WSTRING -// wchar_t pointer vs ::wstring -TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsWString) { - const wchar_t* s = L"hi \"world"; - EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped. - FormatForComparisonFailureMessage(s, ::wstring()).c_str()); - - // wchar_t* - wchar_t str[] = L"hi\1"; - wchar_t* p = str; - EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped. - FormatForComparisonFailureMessage(p, ::wstring()).c_str()); -} -#endif - -#if GTEST_HAS_STD_WSTRING -// wchar_t pointer vs std::wstring -TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) { - const wchar_t* s = L"hi \"world"; - EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped. - FormatForComparisonFailureMessage(s, ::std::wstring()).c_str()); - - // wchar_t* - wchar_t str[] = L"hi\1"; - wchar_t* p = str; - EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped. - FormatForComparisonFailureMessage(p, ::std::wstring()).c_str()); -} -#endif - -// Tests formatting a char array when it's compared with a pointer or array. -// In this case we want to print the array as a row pointer, as the comparison -// is by pointer. - -// char array vs pointer -TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) { - char str[] = "hi \"world\""; - char* p = NULL; - EXPECT_EQ(PrintPointer(str), - FormatForComparisonFailureMessage(str, p).c_str()); -} - -// char array vs char array -TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) { - const char str[] = "hi \"world\""; - EXPECT_EQ(PrintPointer(str), - FormatForComparisonFailureMessage(str, str).c_str()); -} - -// wchar_t array vs pointer -TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) { - wchar_t str[] = L"hi \"world\""; - wchar_t* p = NULL; - EXPECT_EQ(PrintPointer(str), - FormatForComparisonFailureMessage(str, p).c_str()); -} - -// wchar_t array vs wchar_t array -TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) { - const wchar_t str[] = L"hi \"world\""; - EXPECT_EQ(PrintPointer(str), - FormatForComparisonFailureMessage(str, str).c_str()); -} - -// Tests formatting a char array when it's compared with a string object. -// In this case we want to print the array as a C string. - -#if GTEST_HAS_GLOBAL_STRING -// char array vs string -TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsString) { - const char str[] = "hi \"w\0rld\""; - EXPECT_STREQ("\"hi \\\"w\"", // The content should be escaped. - // Embedded NUL terminates the string. - FormatForComparisonFailureMessage(str, ::string()).c_str()); -} -#endif - -// char array vs std::string -TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) { - const char str[] = "hi \"world\""; - EXPECT_STREQ("\"hi \\\"world\\\"\"", // The content should be escaped. - FormatForComparisonFailureMessage(str, ::std::string()).c_str()); -} - -#if GTEST_HAS_GLOBAL_WSTRING -// wchar_t array vs wstring -TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWString) { - const wchar_t str[] = L"hi \"world\""; - EXPECT_STREQ("L\"hi \\\"world\\\"\"", // The content should be escaped. - FormatForComparisonFailureMessage(str, ::wstring()).c_str()); -} -#endif - -#if GTEST_HAS_STD_WSTRING -// wchar_t array vs std::wstring -TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) { - const wchar_t str[] = L"hi \"w\0rld\""; - EXPECT_STREQ( - "L\"hi \\\"w\"", // The content should be escaped. - // Embedded NUL terminates the string. - FormatForComparisonFailureMessage(str, ::std::wstring()).c_str()); -} -#endif - -// 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_PRINT_TO_STRING_(123, "123"); -} - -TEST(PrintToStringTest, WorksForPointerToConstChar) { - const char* p = "hello"; - EXPECT_PRINT_TO_STRING_(p, "\"hello\""); -} - -TEST(PrintToStringTest, WorksForPointerToNonConstChar) { - char s[] = "hello"; - char* p = s; - EXPECT_PRINT_TO_STRING_(p, "\"hello\""); -} - -TEST(PrintToStringTest, EscapesForPointerToConstChar) { - const char* p = "hello\n"; - EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\""); -} - -TEST(PrintToStringTest, EscapesForPointerToNonConstChar) { - char s[] = "hello\1"; - char* p = s; - EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\""); -} - -TEST(PrintToStringTest, WorksForArray) { - int n[3] = { 1, 2, 3 }; - EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }"); -} - -TEST(PrintToStringTest, WorksForCharArray) { - char s[] = "hello"; - EXPECT_PRINT_TO_STRING_(s, "\"hello\""); -} - -TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) { - const char str_with_nul[] = "hello\0 world"; - EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\""); - - char mutable_str_with_nul[] = "hello\0 world"; - EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\""); -} - - TEST(PrintToStringTest, ContainsNonLatin) { - // Sanity test with valid UTF-8. Prints both in hex and as text. - std::string non_ascii_str = ::std::string("오전 4:30"); - EXPECT_PRINT_TO_STRING_(non_ascii_str, - "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n" - " As Text: \"오전 4:30\""); - non_ascii_str = ::std::string("From ä — ẑ"); - EXPECT_PRINT_TO_STRING_(non_ascii_str, - "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\"" - "\n As Text: \"From ä — ẑ\""); -} - -TEST(IsValidUTF8Test, IllFormedUTF8) { - // The following test strings are ill-formed UTF-8 and are printed - // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is - // expected to fail, thus output does not contain "As Text:". - - static const char *const kTestdata[][2] = { - // 2-byte lead byte followed by a single-byte character. - {"\xC3\x74", "\"\\xC3t\""}, - // Valid 2-byte character followed by an orphan trail byte. - {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""}, - // Lead byte without trail byte. - {"abc\xC3", "\"abc\\xC3\""}, - // 3-byte lead byte, single-byte character, orphan trail byte. - {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""}, - // Truncated 3-byte character. - {"\xE2\x80", "\"\\xE2\\x80\""}, - // Truncated 3-byte character followed by valid 2-byte char. - {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""}, - // Truncated 3-byte character followed by a single-byte character. - {"\xE2\x80\x7A", "\"\\xE2\\x80z\""}, - // 3-byte lead byte followed by valid 3-byte character. - {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""}, - // 4-byte lead byte followed by valid 3-byte character. - {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""}, - // Truncated 4-byte character. - {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""}, - // Invalid UTF-8 byte sequences embedded in other chars. - {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""}, - {"abc\xC3\x84\xE2\x80\xC3\x84xyz", - "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""}, - // Non-shortest UTF-8 byte sequences are also ill-formed. - // The classics: xC0, xC1 lead byte. - {"\xC0\x80", "\"\\xC0\\x80\""}, - {"\xC1\x81", "\"\\xC1\\x81\""}, - // Non-shortest sequences. - {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""}, - {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""}, - // Last valid code point before surrogate range, should be printed as text, - // too. - {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"퟿\""}, - // Start of surrogate lead. Surrogates are not printed as text. - {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""}, - // Last non-private surrogate lead. - {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""}, - // First private-use surrogate lead. - {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""}, - // Last private-use surrogate lead. - {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""}, - // Mid-point of surrogate trail. - {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""}, - // First valid code point after surrogate range, should be printed as text, - // too. - {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""} - }; - - for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) { - EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]); - } -} - -#undef EXPECT_PRINT_TO_STRING_ - -TEST(UniversalTersePrintTest, WorksForNonReference) { - ::std::stringstream ss; - UniversalTersePrint(123, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalTersePrintTest, WorksForReference) { - const int& n = 123; - ::std::stringstream ss; - UniversalTersePrint(n, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalTersePrintTest, WorksForCString) { - const char* s1 = "abc"; - ::std::stringstream ss1; - UniversalTersePrint(s1, &ss1); - EXPECT_EQ("\"abc\"", ss1.str()); - - char* s2 = const_cast(s1); - ::std::stringstream ss2; - UniversalTersePrint(s2, &ss2); - EXPECT_EQ("\"abc\"", ss2.str()); - - const char* s3 = NULL; - ::std::stringstream ss3; - UniversalTersePrint(s3, &ss3); - EXPECT_EQ("NULL", ss3.str()); -} - -TEST(UniversalPrintTest, WorksForNonReference) { - ::std::stringstream ss; - UniversalPrint(123, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalPrintTest, WorksForReference) { - const int& n = 123; - ::std::stringstream ss; - UniversalPrint(n, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalPrintTest, WorksForCString) { - const char* s1 = "abc"; - ::std::stringstream ss1; - UniversalPrint(s1, &ss1); - EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str())); - - char* s2 = const_cast(s1); - ::std::stringstream ss2; - UniversalPrint(s2, &ss2); - EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str())); - - const char* s3 = NULL; - ::std::stringstream ss3; - UniversalPrint(s3, &ss3); - EXPECT_EQ("NULL", ss3.str()); -} - -TEST(UniversalPrintTest, WorksForCharArray) { - const char str[] = "\"Line\0 1\"\nLine 2"; - ::std::stringstream ss1; - UniversalPrint(str, &ss1); - EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str()); - - const char mutable_str[] = "\"Line\0 1\"\nLine 2"; - ::std::stringstream ss2; - UniversalPrint(mutable_str, &ss2); - EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str()); -} - -#if GTEST_HAS_TR1_TUPLE - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsEmptyTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tr1::make_tuple()); - EXPECT_EQ(0u, result.size()); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsOneTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tr1::make_tuple(1)); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ("1", result[0]); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTwoTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tr1::make_tuple(1, 'a')); - ASSERT_EQ(2u, result.size()); - EXPECT_EQ("1", result[0]); - EXPECT_EQ("'a' (97, 0x61)", result[1]); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTersely) { - const int n = 1; - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tr1::tuple(n, "a")); - ASSERT_EQ(2u, result.size()); - EXPECT_EQ("1", result[0]); - EXPECT_EQ("\"a\"", result[1]); -} - -#endif // GTEST_HAS_TR1_TUPLE - -#if GTEST_HAS_STD_TUPLE_ - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple()); - EXPECT_EQ(0u, result.size()); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::make_tuple(1)); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ("1", result[0]); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::make_tuple(1, 'a')); - ASSERT_EQ(2u, result.size()); - EXPECT_EQ("1", result[0]); - EXPECT_EQ("'a' (97, 0x61)", result[1]); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) { - const int n = 1; - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tuple(n, "a")); - ASSERT_EQ(2u, result.size()); - EXPECT_EQ("1", result[0]); - EXPECT_EQ("\"a\"", result[1]); -} - -#endif // GTEST_HAS_STD_TUPLE_ - -#if GTEST_HAS_ABSL - -TEST(PrintOptionalTest, Basic) { - absl::optional value; - EXPECT_EQ("(nullopt)", PrintToString(value)); - value = {7}; - EXPECT_EQ("(7)", PrintToString(value)); - EXPECT_EQ("(1.1)", PrintToString(absl::optional{1.1})); - EXPECT_EQ("(\"A\")", PrintToString(absl::optional{"A"})); -} -#endif // GTEST_HAS_ABSL - -} // namespace gtest_printers_test -} // namespace testing diff --git a/googletest/test/gtest-tuple_test.cc b/googletest/test/gtest-tuple_test.cc deleted file mode 100644 index bfaa3e0..0000000 --- a/googletest/test/gtest-tuple_test.cc +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) - -#include "gtest/internal/gtest-tuple.h" -#include -#include "gtest/gtest.h" - -namespace { - -using ::std::tr1::get; -using ::std::tr1::make_tuple; -using ::std::tr1::tuple; -using ::std::tr1::tuple_element; -using ::std::tr1::tuple_size; -using ::testing::StaticAssertTypeEq; - -// Tests that tuple_element >::type returns TK. -TEST(tuple_element_Test, ReturnsElementType) { - StaticAssertTypeEq >::type>(); - StaticAssertTypeEq >::type>(); - StaticAssertTypeEq >::type>(); -} - -// Tests that tuple_size::value gives the number of fields in tuple -// type T. -TEST(tuple_size_Test, ReturnsNumberOfFields) { - EXPECT_EQ(0, +tuple_size >::value); - EXPECT_EQ(1, +tuple_size >::value); - EXPECT_EQ(1, +tuple_size >::value); - EXPECT_EQ(1, +(tuple_size > >::value)); - EXPECT_EQ(2, +(tuple_size >::value)); - EXPECT_EQ(3, +(tuple_size >::value)); -} - -// Tests comparing a tuple with itself. -TEST(ComparisonTest, ComparesWithSelf) { - const tuple a(5, 'a', false); - - EXPECT_TRUE(a == a); - EXPECT_FALSE(a != a); -} - -// Tests comparing two tuples with the same value. -TEST(ComparisonTest, ComparesEqualTuples) { - const tuple a(5, true), b(5, true); - - EXPECT_TRUE(a == b); - EXPECT_FALSE(a != b); -} - -// Tests comparing two different tuples that have no reference fields. -TEST(ComparisonTest, ComparesUnequalTuplesWithoutReferenceFields) { - typedef tuple FooTuple; - - const FooTuple a(0, 'x'); - const FooTuple b(1, 'a'); - - EXPECT_TRUE(a != b); - EXPECT_FALSE(a == b); - - const FooTuple c(1, 'b'); - - EXPECT_TRUE(b != c); - EXPECT_FALSE(b == c); -} - -// Tests comparing two different tuples that have reference fields. -TEST(ComparisonTest, ComparesUnequalTuplesWithReferenceFields) { - typedef tuple FooTuple; - - int i = 5; - const char ch = 'a'; - const FooTuple a(i, ch); - - int j = 6; - const FooTuple b(j, ch); - - EXPECT_TRUE(a != b); - EXPECT_FALSE(a == b); - - j = 5; - const char ch2 = 'b'; - const FooTuple c(j, ch2); - - EXPECT_TRUE(b != c); - EXPECT_FALSE(b == c); -} - -// Tests that a tuple field with a reference type is an alias of the -// variable it's supposed to reference. -TEST(ReferenceFieldTest, IsAliasOfReferencedVariable) { - int n = 0; - tuple t(true, n); - - n = 1; - EXPECT_EQ(n, get<1>(t)) - << "Changing a underlying variable should update the reference field."; - - // Makes sure that the implementation doesn't do anything funny with - // the & operator for the return type of get<>(). - EXPECT_EQ(&n, &(get<1>(t))) - << "The address of a reference field should equal the address of " - << "the underlying variable."; - - get<1>(t) = 2; - EXPECT_EQ(2, n) - << "Changing a reference field should update the underlying variable."; -} - -// Tests that tuple's default constructor default initializes each field. -// This test needs to compile without generating warnings. -TEST(TupleConstructorTest, DefaultConstructorDefaultInitializesEachField) { - // The TR1 report requires that tuple's default constructor default - // initializes each field, even if it's a primitive type. If the - // implementation forgets to do this, this test will catch it by - // generating warnings about using uninitialized variables (assuming - // a decent compiler). - - tuple<> empty; - - tuple a1, b1; - b1 = a1; - EXPECT_EQ(0, get<0>(b1)); - - tuple a2, b2; - b2 = a2; - EXPECT_EQ(0, get<0>(b2)); - EXPECT_EQ(0.0, get<1>(b2)); - - tuple a3, b3; - b3 = a3; - EXPECT_EQ(0.0, get<0>(b3)); - EXPECT_EQ('\0', get<1>(b3)); - EXPECT_TRUE(get<2>(b3) == NULL); - - tuple a10, b10; - b10 = a10; - EXPECT_EQ(0, get<0>(b10)); - EXPECT_EQ(0, get<1>(b10)); - EXPECT_EQ(0, get<2>(b10)); - EXPECT_EQ(0, get<3>(b10)); - EXPECT_EQ(0, get<4>(b10)); - EXPECT_EQ(0, get<5>(b10)); - EXPECT_EQ(0, get<6>(b10)); - EXPECT_EQ(0, get<7>(b10)); - EXPECT_EQ(0, get<8>(b10)); - EXPECT_EQ(0, get<9>(b10)); -} - -// Tests constructing a tuple from its fields. -TEST(TupleConstructorTest, ConstructsFromFields) { - int n = 1; - // Reference field. - tuple a(n); - EXPECT_EQ(&n, &(get<0>(a))); - - // Non-reference fields. - tuple b(5, 'a'); - EXPECT_EQ(5, get<0>(b)); - EXPECT_EQ('a', get<1>(b)); - - // Const reference field. - const int m = 2; - tuple c(true, m); - EXPECT_TRUE(get<0>(c)); - EXPECT_EQ(&m, &(get<1>(c))); -} - -// Tests tuple's copy constructor. -TEST(TupleConstructorTest, CopyConstructor) { - tuple a(0.0, true); - tuple b(a); - - EXPECT_DOUBLE_EQ(0.0, get<0>(b)); - EXPECT_TRUE(get<1>(b)); -} - -// Tests constructing a tuple from another tuple that has a compatible -// but different type. -TEST(TupleConstructorTest, ConstructsFromDifferentTupleType) { - tuple a(0, 1, 'a'); - tuple b(a); - - EXPECT_DOUBLE_EQ(0.0, get<0>(b)); - EXPECT_EQ(1, get<1>(b)); - EXPECT_EQ('a', get<2>(b)); -} - -// Tests constructing a 2-tuple from an std::pair. -TEST(TupleConstructorTest, ConstructsFromPair) { - ::std::pair a(1, 'a'); - tuple b(a); - tuple c(a); -} - -// Tests assigning a tuple to another tuple with the same type. -TEST(TupleAssignmentTest, AssignsToSameTupleType) { - const tuple a(5, 7L); - tuple b; - b = a; - EXPECT_EQ(5, get<0>(b)); - EXPECT_EQ(7L, get<1>(b)); -} - -// Tests assigning a tuple to another tuple with a different but -// compatible type. -TEST(TupleAssignmentTest, AssignsToDifferentTupleType) { - const tuple a(1, 7L, true); - tuple b; - b = a; - EXPECT_EQ(1L, get<0>(b)); - EXPECT_EQ(7, get<1>(b)); - EXPECT_TRUE(get<2>(b)); -} - -// Tests assigning an std::pair to a 2-tuple. -TEST(TupleAssignmentTest, AssignsFromPair) { - const ::std::pair a(5, true); - tuple b; - b = a; - EXPECT_EQ(5, get<0>(b)); - EXPECT_TRUE(get<1>(b)); - - tuple c; - c = a; - EXPECT_EQ(5L, get<0>(c)); - EXPECT_TRUE(get<1>(c)); -} - -// A fixture for testing big tuples. -class BigTupleTest : public testing::Test { - protected: - typedef tuple BigTuple; - - BigTupleTest() : - a_(1, 0, 0, 0, 0, 0, 0, 0, 0, 2), - b_(1, 0, 0, 0, 0, 0, 0, 0, 0, 3) {} - - BigTuple a_, b_; -}; - -// Tests constructing big tuples. -TEST_F(BigTupleTest, Construction) { - BigTuple a; - BigTuple b(b_); -} - -// Tests that get(t) returns the N-th (0-based) field of tuple t. -TEST_F(BigTupleTest, get) { - EXPECT_EQ(1, get<0>(a_)); - EXPECT_EQ(2, get<9>(a_)); - - // Tests that get() works on a const tuple too. - const BigTuple a(a_); - EXPECT_EQ(1, get<0>(a)); - EXPECT_EQ(2, get<9>(a)); -} - -// Tests comparing big tuples. -TEST_F(BigTupleTest, Comparisons) { - EXPECT_TRUE(a_ == a_); - EXPECT_FALSE(a_ != a_); - - EXPECT_TRUE(a_ != b_); - EXPECT_FALSE(a_ == b_); -} - -TEST(MakeTupleTest, WorksForScalarTypes) { - tuple a; - a = make_tuple(true, 5); - EXPECT_TRUE(get<0>(a)); - EXPECT_EQ(5, get<1>(a)); - - tuple b; - b = make_tuple('a', 'b', 5); - EXPECT_EQ('a', get<0>(b)); - EXPECT_EQ('b', get<1>(b)); - EXPECT_EQ(5, get<2>(b)); -} - -TEST(MakeTupleTest, WorksForPointers) { - int a[] = { 1, 2, 3, 4 }; - const char* const str = "hi"; - int* const p = a; - - tuple t; - t = make_tuple(str, p); - EXPECT_EQ(str, get<0>(t)); - EXPECT_EQ(p, get<1>(t)); -} - -} // namespace -- cgit v0.12 From 8dea630e88560874eeb18b09bf3ad112e15bacab Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 17:06:17 -0400 Subject: various changes to tests --- googletest/test/BUILD.bazel | 56 +- googletest/test/googletest-death-test_ex_test.cc | 93 ++ .../googletest-param-test-invalid-name1-test.py | 72 ++ .../googletest-param-test-invalid-name1-test_.cc | 51 + .../googletest-param-test-invalid-name2-test.py | 71 ++ .../googletest-param-test-invalid-name2-test_.cc | 56 + googletest/test/googletest-param-test-test.cc | 1110 ++++++++++++++++++++ googletest/test/googletest-param-test-test.h | 53 + googletest/test/googletest-param-test2-test.cc | 61 ++ googletest/test/googletest-test-part-test.cc | 208 ++++ googletest/test/googletest-test2_test.cc | 61 ++ googletest/test/gtest-death-test_ex_test.cc | 93 -- googletest/test/gtest-param-test2_test.cc | 61 -- googletest/test/gtest-param-test_test.cc | 1110 -------------------- googletest/test/gtest-param-test_test.h | 53 - googletest/test/gtest-test-part_test.cc | 208 ---- googletest/test/gtest_all_test.cc | 12 +- googletest/test/gtest_json_outfiles_test.py | 162 --- googletest/test/gtest_json_output_unittest.py | 611 ----------- googletest/test/gtest_uninitialized_test_.cc | 43 - 20 files changed, 1891 insertions(+), 2354 deletions(-) create mode 100644 googletest/test/googletest-death-test_ex_test.cc create mode 100644 googletest/test/googletest-param-test-invalid-name1-test.py create mode 100644 googletest/test/googletest-param-test-invalid-name1-test_.cc create mode 100644 googletest/test/googletest-param-test-invalid-name2-test.py create mode 100644 googletest/test/googletest-param-test-invalid-name2-test_.cc create mode 100644 googletest/test/googletest-param-test-test.cc create mode 100644 googletest/test/googletest-param-test-test.h create mode 100644 googletest/test/googletest-param-test2-test.cc create mode 100644 googletest/test/googletest-test-part-test.cc create mode 100644 googletest/test/googletest-test2_test.cc delete mode 100644 googletest/test/gtest-death-test_ex_test.cc delete mode 100644 googletest/test/gtest-param-test2_test.cc delete mode 100644 googletest/test/gtest-param-test_test.cc delete mode 100644 googletest/test/gtest-param-test_test.h delete mode 100644 googletest/test/gtest-test-part_test.cc delete mode 100644 googletest/test/gtest_json_outfiles_test.py delete mode 100644 googletest/test/gtest_json_output_unittest.py delete mode 100644 googletest/test/gtest_uninitialized_test_.cc diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index a5c6b14..3f6d466 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -79,6 +79,11 @@ cc_test( "googletest-list-tests-unittest_.cc", "googletest-shuffle-test_.cc", "googletest-uninitialized-test_.cc", + "googletest-death-test_ex_test.cc", + "googletest-param-test-test", + "googletest-throw-on-failure-test_.cc", + "googletest-param-test-invalid-name1-test_.cc", + "googletest-param-test-invalid-name2-test_.cc", ], ) + select({ @@ -145,16 +150,14 @@ cc_test( ) cc_test( - name = "gtest-param-test_test", + name = "googletest-param-test-test", size = "small", srcs = [ - "gtest-param-test2_test.cc", - "gtest-param-test_test.cc", - "gtest-param-test_test.h", - ], - deps = [ - "//:gtest", + "googletest-param-test-test.cc", + "googletest-param-test-test.h", + "googletest-param-test2-test.cc", ], + deps = ["//:gtest"], ) cc_test( @@ -483,3 +486,42 @@ py_test( }), deps = [":gtest_test_utils"], ) +# Verifies interaction of death tests and exceptions. +cc_test( + name = "googletest-death-test_ex_catch_test", + size = "medium", + srcs = ["googletest-death-test_ex_test.cc"], + copts = ["-fexceptions"], + defines = ["GTEST_ENABLE_CATCH_EXCEPTIONS_=1"], + deps = ["//:gtest"], +) + +cc_binary( + name = "googletest-param-test-invalid-name1-test_", + testonly = 1, + srcs = ["googletest-param-test-invalid-name1-test_.cc"], + deps = ["//:gtest"], +) + +cc_binary( + name = "googletest-param-test-invalid-name2-test_", + testonly = 1, + srcs = ["googletest-param-test-invalid-name2-test_.cc"], + deps = ["//:gtest"], +) + +py_test( + name = "googletest-param-test-invalid-name1-test", + size = "small", + srcs = ["googletest-param-test-invalid-name1-test.py"], + data = [":googletest-param-test-invalid-name1-test_"], + deps = [":gtest_test_utils"], +) + +py_test( + name = "googletest-param-test-invalid-name2-test", + size = "small", + srcs = ["googletest-param-test-invalid-name2-test.py"], + data = [":googletest-param-test-invalid-name2-test_"], + deps = [":gtest_test_utils"], +) diff --git a/googletest/test/googletest-death-test_ex_test.cc b/googletest/test/googletest-death-test_ex_test.cc new file mode 100644 index 0000000..3391074 --- /dev/null +++ b/googletest/test/googletest-death-test_ex_test.cc @@ -0,0 +1,93 @@ +// 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 that verify interaction of exceptions and death tests. + +#include "gtest/gtest-death-test.h" +#include "gtest/gtest.h" + +#if GTEST_HAS_DEATH_TEST + +# if GTEST_HAS_SEH +# include // For RaiseException(). +# endif + +# include "gtest/gtest-spi.h" + +# if GTEST_HAS_EXCEPTIONS + +# include // For std::exception. + +// Tests that death tests report thrown exceptions as failures and that the +// exceptions do not escape death test macros. +TEST(CxxExceptionDeathTest, ExceptionIsFailure) { + try { + EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw 1, ""), "threw an exception"); + } catch (...) { // NOLINT + FAIL() << "An exception escaped a death test macro invocation " + << "with catch_exceptions " + << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled"); + } +} + +class TestException : public std::exception { + public: + virtual const char* what() const throw() { return "exceptional message"; } +}; + +TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) { + // Verifies that the exception message is quoted in the failure text. + EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), + "exceptional message"); + // Verifies that the location is mentioned in the failure text. + EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), + "googletest-death-test_ex_test.cc"); +} +# endif // GTEST_HAS_EXCEPTIONS + +# if GTEST_HAS_SEH +// Tests that enabling interception of SEH exceptions with the +// catch_exceptions flag does not interfere with SEH exceptions being +// treated as death by death tests. +TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) { + EXPECT_DEATH(RaiseException(42, 0x0, 0, NULL), "") + << "with catch_exceptions " + << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled"); +} +# endif + +#endif // GTEST_HAS_DEATH_TEST + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + testing::GTEST_FLAG(catch_exceptions) = GTEST_ENABLE_CATCH_EXCEPTIONS_ != 0; + return RUN_ALL_TESTS(); +} diff --git a/googletest/test/googletest-param-test-invalid-name1-test.py b/googletest/test/googletest-param-test-invalid-name1-test.py new file mode 100644 index 0000000..63be043 --- /dev/null +++ b/googletest/test/googletest-param-test-invalid-name1-test.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. + +"""Verifies that Google Test warns the user when not initialized properly.""" + +__author__ = 'jmadill@google.com (Jamie Madill)' + +import os + +IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' + +if IS_LINUX: + import gtest_test_utils +else: + import gtest_test_utils + +binary_name = 'googletest-param-test-invalid-name1-test_' +COMMAND = gtest_test_utils.GetTestExecutablePath(binary_name) + + +def Assert(condition): + if not condition: + raise AssertionError + + +def TestExitCodeAndOutput(command): + """Runs the given command and verifies its exit code and output.""" + + err = ('Parameterized test name \'"InvalidWithQuotes"\' is invalid') + + p = gtest_test_utils.Subprocess(command) + Assert(p.terminated_by_signal) + + # Verify the output message contains appropriate output + Assert(err in p.output) + + +class GTestParamTestInvalidName1Test(gtest_test_utils.TestCase): + + def testExitCodeAndOutput(self): + TestExitCodeAndOutput(COMMAND) + + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/googletest-param-test-invalid-name1-test_.cc b/googletest/test/googletest-param-test-invalid-name1-test_.cc new file mode 100644 index 0000000..68dd470 --- /dev/null +++ b/googletest/test/googletest-param-test-invalid-name1-test_.cc @@ -0,0 +1,51 @@ +// Copyright 2015, 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: jmadill@google.com (Jamie Madill) + +#include "gtest/gtest.h" + +namespace { +class DummyTest : public ::testing::TestWithParam {}; + +TEST_P(DummyTest, Dummy) { +} + +INSTANTIATE_TEST_CASE_P(InvalidTestName, + DummyTest, + ::testing::Values("InvalidWithQuotes"), + ::testing::PrintToStringParamName()); + +} // namespace + +int main(int argc, char *argv[]) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} + diff --git a/googletest/test/googletest-param-test-invalid-name2-test.py b/googletest/test/googletest-param-test-invalid-name2-test.py new file mode 100644 index 0000000..b1a80c1 --- /dev/null +++ b/googletest/test/googletest-param-test-invalid-name2-test.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. + +"""Verifies that Google Test warns the user when not initialized properly.""" + +__author__ = 'jmadill@google.com (Jamie Madill)' + +import os + +IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' + +if IS_LINUX: + import gtest_test_utils +else: + import gtest_test_utils + +binary_name = 'googletest-param-test-invalid-name2-test_' +COMMAND = gtest_test_utils.GetTestExecutablePath(binary_name) + + +def Assert(condition): + if not condition: + raise AssertionError + + +def TestExitCodeAndOutput(command): + """Runs the given command and verifies its exit code and output.""" + + err = ('Duplicate parameterized test name \'a\'') + + p = gtest_test_utils.Subprocess(command) + Assert(p.terminated_by_signal) + + # Check for appropriate output + Assert(err in p.output) + + +class GTestParamTestInvalidName2Test(gtest_test_utils.TestCase): + + def testExitCodeAndOutput(self): + TestExitCodeAndOutput(COMMAND) + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/googletest-param-test-invalid-name2-test_.cc b/googletest/test/googletest-param-test-invalid-name2-test_.cc new file mode 100644 index 0000000..9a8ec4e --- /dev/null +++ b/googletest/test/googletest-param-test-invalid-name2-test_.cc @@ -0,0 +1,56 @@ +// Copyright 2015, 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: jmadill@google.com (Jamie Madill) + +#include "gtest/gtest.h" + +namespace { +class DummyTest : public ::testing::TestWithParam {}; + +std::string StringParamTestSuffix( + const testing::TestParamInfo& info) { + return std::string(info.param); +} + +TEST_P(DummyTest, Dummy) { +} + +INSTANTIATE_TEST_CASE_P(DuplicateTestNames, + DummyTest, + ::testing::Values("a", "b", "a", "c"), + StringParamTestSuffix); +} // namespace + +int main(int argc, char *argv[]) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} + + diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc new file mode 100644 index 0000000..893b132 --- /dev/null +++ b/googletest/test/googletest-param-test-test.cc @@ -0,0 +1,1110 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vladl@google.com (Vlad Losev) +// +// Tests for Google Test itself. This file verifies that the parameter +// generators objects produce correct parameter sequences and that +// Google Test runtime instantiates correct tests from those sequences. + +#include "gtest/gtest.h" + +# include +# include +# include +# include +# include +# include + +# include "src/gtest-internal-inl.h" // for UnitTestOptions +# include "test/googletest-param-test-test.h" + +using ::std::vector; +using ::std::sort; + +using ::testing::AddGlobalTestEnvironment; +using ::testing::Bool; +using ::testing::Message; +using ::testing::Range; +using ::testing::TestWithParam; +using ::testing::Values; +using ::testing::ValuesIn; + +# if GTEST_HAS_COMBINE +using ::testing::Combine; +using ::testing::get; +using ::testing::make_tuple; +using ::testing::tuple; +# endif // GTEST_HAS_COMBINE + +using ::testing::internal::ParamGenerator; +using ::testing::internal::UnitTestOptions; + +// Prints a value to a string. +// +// TODO(wan@google.com): remove PrintValue() when we move matchers and +// EXPECT_THAT() from Google Mock to Google Test. At that time, we +// can write EXPECT_THAT(x, Eq(y)) to compare two tuples x and y, as +// EXPECT_THAT() and the matchers know how to print tuples. +template +::std::string PrintValue(const T& value) { + ::std::stringstream stream; + stream << value; + return stream.str(); +} + +# if GTEST_HAS_COMBINE + +// These overloads allow printing tuples in our tests. We cannot +// define an operator<< for tuples, as that definition needs to be in +// the std namespace in order to be picked up by Google Test via +// Argument-Dependent Lookup, yet defining anything in the std +// namespace in non-STL code is undefined behavior. + +template +::std::string PrintValue(const tuple& value) { + ::std::stringstream stream; + stream << "(" << get<0>(value) << ", " << get<1>(value) << ")"; + return stream.str(); +} + +template +::std::string PrintValue(const tuple& value) { + ::std::stringstream stream; + stream << "(" << get<0>(value) << ", " << get<1>(value) + << ", "<< get<2>(value) << ")"; + return stream.str(); +} + +template +::std::string PrintValue( + const tuple& value) { + ::std::stringstream stream; + stream << "(" << get<0>(value) << ", " << get<1>(value) + << ", "<< get<2>(value) << ", " << get<3>(value) + << ", "<< get<4>(value) << ", " << get<5>(value) + << ", "<< get<6>(value) << ", " << get<7>(value) + << ", "<< get<8>(value) << ", " << get<9>(value) << ")"; + return stream.str(); +} + +# endif // GTEST_HAS_COMBINE + +// Verifies that a sequence generated by the generator and accessed +// via the iterator object matches the expected one using Google Test +// assertions. +template +void VerifyGenerator(const ParamGenerator& generator, + const T (&expected_values)[N]) { + typename ParamGenerator::iterator it = generator.begin(); + for (size_t i = 0; i < N; ++i) { + ASSERT_FALSE(it == generator.end()) + << "At element " << i << " when accessing via an iterator " + << "created with the copy constructor.\n"; + // We cannot use EXPECT_EQ() here as the values may be tuples, + // which don't support <<. + EXPECT_TRUE(expected_values[i] == *it) + << "where i is " << i + << ", expected_values[i] is " << PrintValue(expected_values[i]) + << ", *it is " << PrintValue(*it) + << ", and 'it' is an iterator created with the copy constructor.\n"; + ++it; + } + EXPECT_TRUE(it == generator.end()) + << "At the presumed end of sequence when accessing via an iterator " + << "created with the copy constructor.\n"; + + // Test the iterator assignment. The following lines verify that + // the sequence accessed via an iterator initialized via the + // assignment operator (as opposed to a copy constructor) matches + // just the same. + it = generator.begin(); + for (size_t i = 0; i < N; ++i) { + ASSERT_FALSE(it == generator.end()) + << "At element " << i << " when accessing via an iterator " + << "created with the assignment operator.\n"; + EXPECT_TRUE(expected_values[i] == *it) + << "where i is " << i + << ", expected_values[i] is " << PrintValue(expected_values[i]) + << ", *it is " << PrintValue(*it) + << ", and 'it' is an iterator created with the copy constructor.\n"; + ++it; + } + EXPECT_TRUE(it == generator.end()) + << "At the presumed end of sequence when accessing via an iterator " + << "created with the assignment operator.\n"; +} + +template +void VerifyGeneratorIsEmpty(const ParamGenerator& generator) { + typename ParamGenerator::iterator it = generator.begin(); + EXPECT_TRUE(it == generator.end()); + + it = generator.begin(); + EXPECT_TRUE(it == generator.end()); +} + +// Generator tests. They test that each of the provided generator functions +// generates an expected sequence of values. The general test pattern +// instantiates a generator using one of the generator functions, +// checks the sequence produced by the generator using its iterator API, +// and then resets the iterator back to the beginning of the sequence +// and checks the sequence again. + +// Tests that iterators produced by generator functions conform to the +// ForwardIterator concept. +TEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) { + const ParamGenerator gen = Range(0, 10); + ParamGenerator::iterator it = gen.begin(); + + // Verifies that iterator initialization works as expected. + ParamGenerator::iterator it2 = it; + EXPECT_TRUE(*it == *it2) << "Initialized iterators must point to the " + << "element same as its source points to"; + + // Verifies that iterator assignment works as expected. + ++it; + EXPECT_FALSE(*it == *it2); + it2 = it; + EXPECT_TRUE(*it == *it2) << "Assigned iterators must point to the " + << "element same as its source points to"; + + // Verifies that prefix operator++() returns *this. + EXPECT_EQ(&it, &(++it)) << "Result of the prefix operator++ must be " + << "refer to the original object"; + + // Verifies that the result of the postfix operator++ points to the value + // pointed to by the original iterator. + int original_value = *it; // Have to compute it outside of macro call to be + // unaffected by the parameter evaluation order. + EXPECT_EQ(original_value, *(it++)); + + // Verifies that prefix and postfix operator++() advance an iterator + // all the same. + it2 = it; + ++it; + ++it2; + EXPECT_TRUE(*it == *it2); +} + +// Tests that Range() generates the expected sequence. +TEST(RangeTest, IntRangeWithDefaultStep) { + const ParamGenerator gen = Range(0, 3); + const int expected_values[] = {0, 1, 2}; + VerifyGenerator(gen, expected_values); +} + +// Edge case. Tests that Range() generates the single element sequence +// as expected when provided with range limits that are equal. +TEST(RangeTest, IntRangeSingleValue) { + const ParamGenerator gen = Range(0, 1); + const int expected_values[] = {0}; + VerifyGenerator(gen, expected_values); +} + +// Edge case. Tests that Range() with generates empty sequence when +// supplied with an empty range. +TEST(RangeTest, IntRangeEmpty) { + const ParamGenerator gen = Range(0, 0); + VerifyGeneratorIsEmpty(gen); +} + +// Tests that Range() with custom step (greater then one) generates +// the expected sequence. +TEST(RangeTest, IntRangeWithCustomStep) { + const ParamGenerator gen = Range(0, 9, 3); + const int expected_values[] = {0, 3, 6}; + VerifyGenerator(gen, expected_values); +} + +// Tests that Range() with custom step (greater then one) generates +// the expected sequence when the last element does not fall on the +// upper range limit. Sequences generated by Range() must not have +// elements beyond the range limits. +TEST(RangeTest, IntRangeWithCustomStepOverUpperBound) { + const ParamGenerator gen = Range(0, 4, 3); + const int expected_values[] = {0, 3}; + VerifyGenerator(gen, expected_values); +} + +// Verifies that Range works with user-defined types that define +// copy constructor, operator=(), operator+(), and operator<(). +class DogAdder { + public: + explicit DogAdder(const char* a_value) : value_(a_value) {} + DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {} + + DogAdder operator=(const DogAdder& other) { + if (this != &other) + value_ = other.value_; + return *this; + } + DogAdder operator+(const DogAdder& other) const { + Message msg; + msg << value_.c_str() << other.value_.c_str(); + return DogAdder(msg.GetString().c_str()); + } + bool operator<(const DogAdder& other) const { + return value_ < other.value_; + } + const std::string& value() const { return value_; } + + private: + std::string value_; +}; + +TEST(RangeTest, WorksWithACustomType) { + const ParamGenerator gen = + Range(DogAdder("cat"), DogAdder("catdogdog"), DogAdder("dog")); + ParamGenerator::iterator it = gen.begin(); + + ASSERT_FALSE(it == gen.end()); + EXPECT_STREQ("cat", it->value().c_str()); + + ASSERT_FALSE(++it == gen.end()); + EXPECT_STREQ("catdog", it->value().c_str()); + + EXPECT_TRUE(++it == gen.end()); +} + +class IntWrapper { + public: + explicit IntWrapper(int a_value) : value_(a_value) {} + IntWrapper(const IntWrapper& other) : value_(other.value_) {} + + IntWrapper operator=(const IntWrapper& other) { + value_ = other.value_; + return *this; + } + // operator+() adds a different type. + IntWrapper operator+(int other) const { return IntWrapper(value_ + other); } + bool operator<(const IntWrapper& other) const { + return value_ < other.value_; + } + int value() const { return value_; } + + private: + int value_; +}; + +TEST(RangeTest, WorksWithACustomTypeWithDifferentIncrementType) { + const ParamGenerator gen = Range(IntWrapper(0), IntWrapper(2)); + ParamGenerator::iterator it = gen.begin(); + + ASSERT_FALSE(it == gen.end()); + EXPECT_EQ(0, it->value()); + + ASSERT_FALSE(++it == gen.end()); + EXPECT_EQ(1, it->value()); + + EXPECT_TRUE(++it == gen.end()); +} + +// Tests that ValuesIn() with an array parameter generates +// the expected sequence. +TEST(ValuesInTest, ValuesInArray) { + int array[] = {3, 5, 8}; + const ParamGenerator gen = ValuesIn(array); + VerifyGenerator(gen, array); +} + +// Tests that ValuesIn() with a const array parameter generates +// the expected sequence. +TEST(ValuesInTest, ValuesInConstArray) { + const int array[] = {3, 5, 8}; + const ParamGenerator gen = ValuesIn(array); + VerifyGenerator(gen, array); +} + +// Edge case. Tests that ValuesIn() with an array parameter containing a +// single element generates the single element sequence. +TEST(ValuesInTest, ValuesInSingleElementArray) { + int array[] = {42}; + const ParamGenerator gen = ValuesIn(array); + VerifyGenerator(gen, array); +} + +// Tests that ValuesIn() generates the expected sequence for an STL +// container (vector). +TEST(ValuesInTest, ValuesInVector) { + typedef ::std::vector ContainerType; + ContainerType values; + values.push_back(3); + values.push_back(5); + values.push_back(8); + const ParamGenerator gen = ValuesIn(values); + + const int expected_values[] = {3, 5, 8}; + VerifyGenerator(gen, expected_values); +} + +// Tests that ValuesIn() generates the expected sequence. +TEST(ValuesInTest, ValuesInIteratorRange) { + typedef ::std::vector ContainerType; + ContainerType values; + values.push_back(3); + values.push_back(5); + values.push_back(8); + const ParamGenerator gen = ValuesIn(values.begin(), values.end()); + + const int expected_values[] = {3, 5, 8}; + VerifyGenerator(gen, expected_values); +} + +// Edge case. Tests that ValuesIn() provided with an iterator range specifying a +// single value generates a single-element sequence. +TEST(ValuesInTest, ValuesInSingleElementIteratorRange) { + typedef ::std::vector ContainerType; + ContainerType values; + values.push_back(42); + const ParamGenerator gen = ValuesIn(values.begin(), values.end()); + + const int expected_values[] = {42}; + VerifyGenerator(gen, expected_values); +} + +// Edge case. Tests that ValuesIn() provided with an empty iterator range +// generates an empty sequence. +TEST(ValuesInTest, ValuesInEmptyIteratorRange) { + typedef ::std::vector ContainerType; + ContainerType values; + const ParamGenerator gen = ValuesIn(values.begin(), values.end()); + + VerifyGeneratorIsEmpty(gen); +} + +// Tests that the Values() generates the expected sequence. +TEST(ValuesTest, ValuesWorks) { + const ParamGenerator gen = Values(3, 5, 8); + + const int expected_values[] = {3, 5, 8}; + VerifyGenerator(gen, expected_values); +} + +// Tests that Values() generates the expected sequences from elements of +// different types convertible to ParamGenerator's parameter type. +TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) { + const ParamGenerator gen = Values(3, 5.0f, 8.0); + + const double expected_values[] = {3.0, 5.0, 8.0}; + VerifyGenerator(gen, expected_values); +} + +TEST(ValuesTest, ValuesWorksForMaxLengthList) { + const ParamGenerator gen = Values( + 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, + 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, + 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, + 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, + 410, 420, 430, 440, 450, 460, 470, 480, 490, 500); + + const int expected_values[] = { + 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, + 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, + 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, + 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, + 410, 420, 430, 440, 450, 460, 470, 480, 490, 500}; + VerifyGenerator(gen, expected_values); +} + +// Edge case test. Tests that single-parameter Values() generates the sequence +// with the single value. +TEST(ValuesTest, ValuesWithSingleParameter) { + const ParamGenerator gen = Values(42); + + const int expected_values[] = {42}; + VerifyGenerator(gen, expected_values); +} + +// Tests that Bool() generates sequence (false, true). +TEST(BoolTest, BoolWorks) { + const ParamGenerator gen = Bool(); + + const bool expected_values[] = {false, true}; + VerifyGenerator(gen, expected_values); +} + +# if GTEST_HAS_COMBINE + +// Tests that Combine() with two parameters generates the expected sequence. +TEST(CombineTest, CombineWithTwoParameters) { + const char* foo = "foo"; + const char* bar = "bar"; + const ParamGenerator > gen = + Combine(Values(foo, bar), Values(3, 4)); + + tuple expected_values[] = { + make_tuple(foo, 3), make_tuple(foo, 4), + make_tuple(bar, 3), make_tuple(bar, 4)}; + VerifyGenerator(gen, expected_values); +} + +// Tests that Combine() with three parameters generates the expected sequence. +TEST(CombineTest, CombineWithThreeParameters) { + const ParamGenerator > gen = Combine(Values(0, 1), + Values(3, 4), + Values(5, 6)); + tuple expected_values[] = { + make_tuple(0, 3, 5), make_tuple(0, 3, 6), + make_tuple(0, 4, 5), make_tuple(0, 4, 6), + make_tuple(1, 3, 5), make_tuple(1, 3, 6), + make_tuple(1, 4, 5), make_tuple(1, 4, 6)}; + VerifyGenerator(gen, expected_values); +} + +// Tests that the Combine() with the first parameter generating a single value +// sequence generates a sequence with the number of elements equal to the +// number of elements in the sequence generated by the second parameter. +TEST(CombineTest, CombineWithFirstParameterSingleValue) { + const ParamGenerator > gen = Combine(Values(42), + Values(0, 1)); + + tuple expected_values[] = {make_tuple(42, 0), make_tuple(42, 1)}; + VerifyGenerator(gen, expected_values); +} + +// Tests that the Combine() with the second parameter generating a single value +// sequence generates a sequence with the number of elements equal to the +// number of elements in the sequence generated by the first parameter. +TEST(CombineTest, CombineWithSecondParameterSingleValue) { + const ParamGenerator > gen = Combine(Values(0, 1), + Values(42)); + + tuple expected_values[] = {make_tuple(0, 42), make_tuple(1, 42)}; + VerifyGenerator(gen, expected_values); +} + +// Tests that when the first parameter produces an empty sequence, +// Combine() produces an empty sequence, too. +TEST(CombineTest, CombineWithFirstParameterEmptyRange) { + const ParamGenerator > gen = Combine(Range(0, 0), + Values(0, 1)); + VerifyGeneratorIsEmpty(gen); +} + +// Tests that when the second parameter produces an empty sequence, +// Combine() produces an empty sequence, too. +TEST(CombineTest, CombineWithSecondParameterEmptyRange) { + const ParamGenerator > gen = Combine(Values(0, 1), + Range(1, 1)); + VerifyGeneratorIsEmpty(gen); +} + +// Edge case. Tests that combine works with the maximum number +// of parameters supported by Google Test (currently 10). +TEST(CombineTest, CombineWithMaxNumberOfParameters) { + const char* foo = "foo"; + const char* bar = "bar"; + const ParamGenerator > gen = Combine(Values(foo, bar), + Values(1), Values(2), + Values(3), Values(4), + Values(5), Values(6), + Values(7), Values(8), + Values(9)); + + tuple + expected_values[] = {make_tuple(foo, 1, 2, 3, 4, 5, 6, 7, 8, 9), + make_tuple(bar, 1, 2, 3, 4, 5, 6, 7, 8, 9)}; + VerifyGenerator(gen, expected_values); +} + +#if GTEST_LANG_CXX11 + +class NonDefaultConstructAssignString { + public: + NonDefaultConstructAssignString(const std::string& s) : str_(s) {} + + const std::string& str() const { return str_; } + + private: + std::string str_; + + // Not default constructible + NonDefaultConstructAssignString(); + // Not assignable + void operator=(const NonDefaultConstructAssignString&); +}; + +TEST(CombineTest, NonDefaultConstructAssign) { + const ParamGenerator > gen = + Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"), + NonDefaultConstructAssignString("B"))); + + ParamGenerator >::iterator it = + gen.begin(); + + EXPECT_EQ(0, std::get<0>(*it)); + EXPECT_EQ("A", std::get<1>(*it).str()); + ++it; + + EXPECT_EQ(0, std::get<0>(*it)); + EXPECT_EQ("B", std::get<1>(*it).str()); + ++it; + + EXPECT_EQ(1, std::get<0>(*it)); + EXPECT_EQ("A", std::get<1>(*it).str()); + ++it; + + EXPECT_EQ(1, std::get<0>(*it)); + EXPECT_EQ("B", std::get<1>(*it).str()); + ++it; + + EXPECT_TRUE(it == gen.end()); +} + +#endif // GTEST_LANG_CXX11 +# endif // GTEST_HAS_COMBINE + +// Tests that an generator produces correct sequence after being +// assigned from another generator. +TEST(ParamGeneratorTest, AssignmentWorks) { + ParamGenerator gen = Values(1, 2); + const ParamGenerator gen2 = Values(3, 4); + gen = gen2; + + const int expected_values[] = {3, 4}; + VerifyGenerator(gen, expected_values); +} + +// This test verifies that the tests are expanded and run as specified: +// one test per element from the sequence produced by the generator +// specified in INSTANTIATE_TEST_CASE_P. It also verifies that the test's +// fixture constructor, SetUp(), and TearDown() have run and have been +// supplied with the correct parameters. + +// The use of environment object allows detection of the case where no test +// case functionality is run at all. In this case TestCaseTearDown will not +// be able to detect missing tests, naturally. +template +class TestGenerationEnvironment : public ::testing::Environment { + public: + static TestGenerationEnvironment* Instance() { + static TestGenerationEnvironment* instance = new TestGenerationEnvironment; + return instance; + } + + void FixtureConstructorExecuted() { fixture_constructor_count_++; } + void SetUpExecuted() { set_up_count_++; } + void TearDownExecuted() { tear_down_count_++; } + void TestBodyExecuted() { test_body_count_++; } + + virtual void TearDown() { + // If all MultipleTestGenerationTest tests have been de-selected + // by the filter flag, the following checks make no sense. + bool perform_check = false; + + for (int i = 0; i < kExpectedCalls; ++i) { + Message msg; + msg << "TestsExpandedAndRun/" << i; + if (UnitTestOptions::FilterMatchesTest( + "TestExpansionModule/MultipleTestGenerationTest", + msg.GetString().c_str())) { + perform_check = true; + } + } + if (perform_check) { + EXPECT_EQ(kExpectedCalls, fixture_constructor_count_) + << "Fixture constructor of ParamTestGenerationTest test case " + << "has not been run as expected."; + EXPECT_EQ(kExpectedCalls, set_up_count_) + << "Fixture SetUp method of ParamTestGenerationTest test case " + << "has not been run as expected."; + EXPECT_EQ(kExpectedCalls, tear_down_count_) + << "Fixture TearDown method of ParamTestGenerationTest test case " + << "has not been run as expected."; + EXPECT_EQ(kExpectedCalls, test_body_count_) + << "Test in ParamTestGenerationTest test case " + << "has not been run as expected."; + } + } + + private: + TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0), + tear_down_count_(0), test_body_count_(0) {} + + int fixture_constructor_count_; + int set_up_count_; + int tear_down_count_; + int test_body_count_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationEnvironment); +}; + +const int test_generation_params[] = {36, 42, 72}; + +class TestGenerationTest : public TestWithParam { + public: + enum { + PARAMETER_COUNT = + sizeof(test_generation_params)/sizeof(test_generation_params[0]) + }; + + typedef TestGenerationEnvironment Environment; + + TestGenerationTest() { + Environment::Instance()->FixtureConstructorExecuted(); + current_parameter_ = GetParam(); + } + virtual void SetUp() { + Environment::Instance()->SetUpExecuted(); + EXPECT_EQ(current_parameter_, GetParam()); + } + virtual void TearDown() { + Environment::Instance()->TearDownExecuted(); + EXPECT_EQ(current_parameter_, GetParam()); + } + + static void SetUpTestCase() { + bool all_tests_in_test_case_selected = true; + + for (int i = 0; i < PARAMETER_COUNT; ++i) { + Message test_name; + test_name << "TestsExpandedAndRun/" << i; + if ( !UnitTestOptions::FilterMatchesTest( + "TestExpansionModule/MultipleTestGenerationTest", + test_name.GetString())) { + all_tests_in_test_case_selected = false; + } + } + EXPECT_TRUE(all_tests_in_test_case_selected) + << "When running the TestGenerationTest test case all of its tests\n" + << "must be selected by the filter flag for the test case to pass.\n" + << "If not all of them are enabled, we can't reliably conclude\n" + << "that the correct number of tests have been generated."; + + collected_parameters_.clear(); + } + + static void TearDownTestCase() { + vector expected_values(test_generation_params, + test_generation_params + PARAMETER_COUNT); + // Test execution order is not guaranteed by Google Test, + // so the order of values in collected_parameters_ can be + // different and we have to sort to compare. + sort(expected_values.begin(), expected_values.end()); + sort(collected_parameters_.begin(), collected_parameters_.end()); + + EXPECT_TRUE(collected_parameters_ == expected_values); + } + + protected: + int current_parameter_; + static vector collected_parameters_; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationTest); +}; +vector TestGenerationTest::collected_parameters_; + +TEST_P(TestGenerationTest, TestsExpandedAndRun) { + Environment::Instance()->TestBodyExecuted(); + EXPECT_EQ(current_parameter_, GetParam()); + collected_parameters_.push_back(GetParam()); +} +INSTANTIATE_TEST_CASE_P(TestExpansionModule, TestGenerationTest, + ValuesIn(test_generation_params)); + +// This test verifies that the element sequence (third parameter of +// INSTANTIATE_TEST_CASE_P) is evaluated in InitGoogleTest() and neither at +// the call site of INSTANTIATE_TEST_CASE_P nor in RUN_ALL_TESTS(). For +// that, we declare param_value_ to be a static member of +// GeneratorEvaluationTest and initialize it to 0. We set it to 1 in +// main(), just before invocation of InitGoogleTest(). After calling +// InitGoogleTest(), we set the value to 2. If the sequence is evaluated +// before or after InitGoogleTest, INSTANTIATE_TEST_CASE_P will create a +// test with parameter other than 1, and the test body will fail the +// assertion. +class GeneratorEvaluationTest : public TestWithParam { + public: + static int param_value() { return param_value_; } + static void set_param_value(int param_value) { param_value_ = param_value; } + + private: + static int param_value_; +}; +int GeneratorEvaluationTest::param_value_ = 0; + +TEST_P(GeneratorEvaluationTest, GeneratorsEvaluatedInMain) { + EXPECT_EQ(1, GetParam()); +} +INSTANTIATE_TEST_CASE_P(GenEvalModule, + GeneratorEvaluationTest, + Values(GeneratorEvaluationTest::param_value())); + +// Tests that generators defined in a different translation unit are +// functional. Generator extern_gen is defined in gtest-param-test_test2.cc. +extern ParamGenerator extern_gen; +class ExternalGeneratorTest : public TestWithParam {}; +TEST_P(ExternalGeneratorTest, ExternalGenerator) { + // Sequence produced by extern_gen contains only a single value + // which we verify here. + EXPECT_EQ(GetParam(), 33); +} +INSTANTIATE_TEST_CASE_P(ExternalGeneratorModule, + ExternalGeneratorTest, + extern_gen); + +// Tests that a parameterized test case can be defined in one translation +// unit and instantiated in another. This test will be instantiated in +// gtest-param-test_test2.cc. ExternalInstantiationTest fixture class is +// defined in gtest-param-test_test.h. +TEST_P(ExternalInstantiationTest, IsMultipleOf33) { + EXPECT_EQ(0, GetParam() % 33); +} + +// Tests that a parameterized test case can be instantiated with multiple +// generators. +class MultipleInstantiationTest : public TestWithParam {}; +TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) { +} +INSTANTIATE_TEST_CASE_P(Sequence1, MultipleInstantiationTest, Values(1, 2)); +INSTANTIATE_TEST_CASE_P(Sequence2, MultipleInstantiationTest, Range(3, 5)); + +// Tests that a parameterized test case can be instantiated +// in multiple translation units. This test will be instantiated +// here and in gtest-param-test_test2.cc. +// InstantiationInMultipleTranslationUnitsTest fixture class +// is defined in gtest-param-test_test.h. +TEST_P(InstantiationInMultipleTranslaionUnitsTest, IsMultipleOf42) { + EXPECT_EQ(0, GetParam() % 42); +} +INSTANTIATE_TEST_CASE_P(Sequence1, + InstantiationInMultipleTranslaionUnitsTest, + Values(42, 42*2)); + +// Tests that each iteration of parameterized test runs in a separate test +// object. +class SeparateInstanceTest : public TestWithParam { + public: + SeparateInstanceTest() : count_(0) {} + + static void TearDownTestCase() { + EXPECT_GE(global_count_, 2) + << "If some (but not all) SeparateInstanceTest tests have been " + << "filtered out this test will fail. Make sure that all " + << "GeneratorEvaluationTest are selected or de-selected together " + << "by the test filter."; + } + + protected: + int count_; + static int global_count_; +}; +int SeparateInstanceTest::global_count_ = 0; + +TEST_P(SeparateInstanceTest, TestsRunInSeparateInstances) { + EXPECT_EQ(0, count_++); + global_count_++; +} +INSTANTIATE_TEST_CASE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4)); + +// Tests that all instantiations of a test have named appropriately. Test +// defined with TEST_P(TestCaseName, TestName) and instantiated with +// INSTANTIATE_TEST_CASE_P(SequenceName, TestCaseName, generator) must be named +// SequenceName/TestCaseName.TestName/i, where i is the 0-based index of the +// sequence element used to instantiate the test. +class NamingTest : public TestWithParam {}; + +TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + + EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_case_name()); + + Message index_stream; + index_stream << "TestsReportCorrectNamesAndParameters/" << GetParam(); + EXPECT_STREQ(index_stream.GetString().c_str(), test_info->name()); + + EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param()); +} + +INSTANTIATE_TEST_CASE_P(ZeroToFiveSequence, NamingTest, Range(0, 5)); + +// Tests that macros in test names are expanded correctly. +class MacroNamingTest : public TestWithParam {}; + +#define PREFIX_WITH_FOO(test_name) Foo##test_name +#define PREFIX_WITH_MACRO(test_name) Macro##test_name + +TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + + EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_case_name()); + EXPECT_STREQ("FooSomeTestName", test_info->name()); +} + +INSTANTIATE_TEST_CASE_P(FortyTwo, MacroNamingTest, Values(42)); + +// Tests the same thing for non-parametrized tests. +class MacroNamingTestNonParametrized : public ::testing::Test {}; + +TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized), + PREFIX_WITH_FOO(SomeTestName)) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + + EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_case_name()); + EXPECT_STREQ("FooSomeTestName", test_info->name()); +} + +// Tests that user supplied custom parameter names are working correctly. +// Runs the test with a builtin helper method which uses PrintToString, +// as well as a custom function and custom functor to ensure all possible +// uses work correctly. +class CustomFunctorNamingTest : public TestWithParam {}; +TEST_P(CustomFunctorNamingTest, CustomTestNames) {} + +struct CustomParamNameFunctor { + std::string operator()(const ::testing::TestParamInfo& inf) { + return inf.param; + } +}; + +INSTANTIATE_TEST_CASE_P(CustomParamNameFunctor, + CustomFunctorNamingTest, + Values(std::string("FunctorName")), + CustomParamNameFunctor()); + +INSTANTIATE_TEST_CASE_P(AllAllowedCharacters, + CustomFunctorNamingTest, + Values("abcdefghijklmnopqrstuvwxyz", + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", + "01234567890_"), + CustomParamNameFunctor()); + +inline std::string CustomParamNameFunction( + const ::testing::TestParamInfo& inf) { + return inf.param; +} + +class CustomFunctionNamingTest : public TestWithParam {}; +TEST_P(CustomFunctionNamingTest, CustomTestNames) {} + +INSTANTIATE_TEST_CASE_P(CustomParamNameFunction, + CustomFunctionNamingTest, + Values(std::string("FunctionName")), + CustomParamNameFunction); + +#if GTEST_LANG_CXX11 + +// Test custom naming with a lambda + +class CustomLambdaNamingTest : public TestWithParam {}; +TEST_P(CustomLambdaNamingTest, CustomTestNames) {} + +INSTANTIATE_TEST_CASE_P(CustomParamNameLambda, CustomLambdaNamingTest, + Values(std::string("LambdaName")), + [](const ::testing::TestParamInfo& inf) { + return inf.param; + }); + +#endif // GTEST_LANG_CXX11 + +TEST(CustomNamingTest, CheckNameRegistry) { + ::testing::UnitTest* unit_test = ::testing::UnitTest::GetInstance(); + std::set test_names; + for (int case_num = 0; + case_num < unit_test->total_test_case_count(); + ++case_num) { + const ::testing::TestCase* test_case = unit_test->GetTestCase(case_num); + for (int test_num = 0; + test_num < test_case->total_test_count(); + ++test_num) { + const ::testing::TestInfo* test_info = test_case->GetTestInfo(test_num); + test_names.insert(std::string(test_info->name())); + } + } + EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctorName")); + EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctionName")); +#if GTEST_LANG_CXX11 + EXPECT_EQ(1u, test_names.count("CustomTestNames/LambdaName")); +#endif // GTEST_LANG_CXX11 +} + +// Test a numeric name to ensure PrintToStringParamName works correctly. + +class CustomIntegerNamingTest : public TestWithParam {}; + +TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + Message test_name_stream; + test_name_stream << "TestsReportCorrectNames/" << GetParam(); + EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); +} + +INSTANTIATE_TEST_CASE_P(PrintToString, + CustomIntegerNamingTest, + Range(0, 5), + ::testing::PrintToStringParamName()); + +// Test a custom struct with PrintToString. + +struct CustomStruct { + explicit CustomStruct(int value) : x(value) {} + int x; +}; + +std::ostream& operator<<(std::ostream& stream, const CustomStruct& val) { + stream << val.x; + return stream; +} + +class CustomStructNamingTest : public TestWithParam {}; + +TEST_P(CustomStructNamingTest, TestsReportCorrectNames) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + Message test_name_stream; + test_name_stream << "TestsReportCorrectNames/" << GetParam(); + EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); +} + +INSTANTIATE_TEST_CASE_P(PrintToString, + CustomStructNamingTest, + Values(CustomStruct(0), CustomStruct(1)), + ::testing::PrintToStringParamName()); + +// Test that using a stateful parameter naming function works as expected. + +struct StatefulNamingFunctor { + StatefulNamingFunctor() : sum(0) {} + std::string operator()(const ::testing::TestParamInfo& info) { + int value = info.param + sum; + sum += info.param; + return ::testing::PrintToString(value); + } + int sum; +}; + +class StatefulNamingTest : public ::testing::TestWithParam { + protected: + StatefulNamingTest() : sum_(0) {} + int sum_; +}; + +TEST_P(StatefulNamingTest, TestsReportCorrectNames) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + sum_ += GetParam(); + Message test_name_stream; + test_name_stream << "TestsReportCorrectNames/" << sum_; + EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); +} + +INSTANTIATE_TEST_CASE_P(StatefulNamingFunctor, + StatefulNamingTest, + Range(0, 5), + StatefulNamingFunctor()); + +// Class that cannot be streamed into an ostream. It needs to be copyable +// (and, in case of MSVC, also assignable) in order to be a test parameter +// type. Its default copy constructor and assignment operator do exactly +// what we need. +class Unstreamable { + public: + explicit Unstreamable(int value) : value_(value) {} + + private: + int value_; +}; + +class CommentTest : public TestWithParam {}; + +TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + + EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param()); +} + +INSTANTIATE_TEST_CASE_P(InstantiationWithComments, + CommentTest, + Values(Unstreamable(1))); + +// Verify that we can create a hierarchy of test fixtures, where the base +// class fixture is not parameterized and the derived class is. In this case +// ParameterizedDerivedTest inherits from NonParameterizedBaseTest. We +// perform simple tests on both. +class NonParameterizedBaseTest : public ::testing::Test { + public: + NonParameterizedBaseTest() : n_(17) { } + protected: + int n_; +}; + +class ParameterizedDerivedTest : public NonParameterizedBaseTest, + public ::testing::WithParamInterface { + protected: + ParameterizedDerivedTest() : count_(0) { } + int count_; + static int global_count_; +}; + +int ParameterizedDerivedTest::global_count_ = 0; + +TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { + EXPECT_EQ(17, n_); +} + +TEST_P(ParameterizedDerivedTest, SeesSequence) { + EXPECT_EQ(17, n_); + EXPECT_EQ(0, count_++); + EXPECT_EQ(GetParam(), global_count_++); +} + +class ParameterizedDeathTest : public ::testing::TestWithParam { }; + +TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) { + EXPECT_DEATH_IF_SUPPORTED(GetParam(), + ".* value-parameterized test .*"); +} + +INSTANTIATE_TEST_CASE_P(RangeZeroToFive, ParameterizedDerivedTest, Range(0, 5)); + + +int main(int argc, char **argv) { + // Used in TestGenerationTest test case. + AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance()); + // Used in GeneratorEvaluationTest test case. Tests that the updated value + // will be picked up for instantiating tests in GeneratorEvaluationTest. + GeneratorEvaluationTest::set_param_value(1); + + ::testing::InitGoogleTest(&argc, argv); + + // Used in GeneratorEvaluationTest test case. Tests that value updated + // here will NOT be used for instantiating tests in + // GeneratorEvaluationTest. + GeneratorEvaluationTest::set_param_value(2); + + return RUN_ALL_TESTS(); +} diff --git a/googletest/test/googletest-param-test-test.h b/googletest/test/googletest-param-test-test.h new file mode 100644 index 0000000..ea1e884 --- /dev/null +++ b/googletest/test/googletest-param-test-test.h @@ -0,0 +1,53 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: vladl@google.com (Vlad Losev) +// +// The Google C++ Testing and Mocking Framework (Google Test) +// +// This header file provides classes and functions used internally +// for testing Google Test itself. + +#ifndef GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ +#define GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ + +#include "gtest/gtest.h" + +// Test fixture for testing definition and instantiation of a test +// in separate translation units. +class ExternalInstantiationTest : public ::testing::TestWithParam { +}; + +// Test fixture for testing instantiation of a test in multiple +// translation units. +class InstantiationInMultipleTranslaionUnitsTest + : public ::testing::TestWithParam { +}; + +#endif // GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ diff --git a/googletest/test/googletest-param-test2-test.cc b/googletest/test/googletest-param-test2-test.cc new file mode 100644 index 0000000..c0db7bf --- /dev/null +++ b/googletest/test/googletest-param-test2-test.cc @@ -0,0 +1,61 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vladl@google.com (Vlad Losev) +// +// Tests for Google Test itself. This verifies that the basic constructs of +// Google Test work. + +#include "gtest/gtest.h" +#include "googletest-param-test-test.h" + +using ::testing::Values; +using ::testing::internal::ParamGenerator; + +// Tests that generators defined in a different translation unit +// are functional. The test using extern_gen is defined +// in gtest-param-test_test.cc. +ParamGenerator extern_gen = Values(33); + +// Tests that a parameterized test case can be defined in one translation unit +// and instantiated in another. The test is defined in gtest-param-test_test.cc +// and ExternalInstantiationTest fixture class is defined in +// gtest-param-test_test.h. +INSTANTIATE_TEST_CASE_P(MultiplesOf33, + ExternalInstantiationTest, + Values(33, 66)); + +// Tests that a parameterized test case can be instantiated +// in multiple translation units. Another instantiation is defined +// in gtest-param-test_test.cc and InstantiationInMultipleTranslaionUnitsTest +// fixture is defined in gtest-param-test_test.h +INSTANTIATE_TEST_CASE_P(Sequence2, + InstantiationInMultipleTranslaionUnitsTest, + Values(42*3, 42*4, 42*5)); + diff --git a/googletest/test/googletest-test-part-test.cc b/googletest/test/googletest-test-part-test.cc new file mode 100644 index 0000000..ca8ba93 --- /dev/null +++ b/googletest/test/googletest-test-part-test.cc @@ -0,0 +1,208 @@ +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: mheule@google.com (Markus Heule) +// + +#include "gtest/gtest-test-part.h" + +#include "gtest/gtest.h" + +using testing::Message; +using testing::Test; +using testing::TestPartResult; +using testing::TestPartResultArray; + +namespace { + +// Tests the TestPartResult class. + +// The test fixture for testing TestPartResult. +class TestPartResultTest : public Test { + protected: + TestPartResultTest() + : r1_(TestPartResult::kSuccess, "foo/bar.cc", 10, "Success!"), + r2_(TestPartResult::kNonFatalFailure, "foo/bar.cc", -1, "Failure!"), + r3_(TestPartResult::kFatalFailure, NULL, -1, "Failure!") {} + + TestPartResult r1_, r2_, r3_; +}; + + +TEST_F(TestPartResultTest, ConstructorWorks) { + Message message; + message << "something is terribly wrong"; + message << static_cast(testing::internal::kStackTraceMarker); + message << "some unimportant stack trace"; + + const TestPartResult result(TestPartResult::kNonFatalFailure, + "some_file.cc", + 42, + message.GetString().c_str()); + + EXPECT_EQ(TestPartResult::kNonFatalFailure, result.type()); + EXPECT_STREQ("some_file.cc", result.file_name()); + EXPECT_EQ(42, result.line_number()); + EXPECT_STREQ(message.GetString().c_str(), result.message()); + EXPECT_STREQ("something is terribly wrong", result.summary()); +} + +TEST_F(TestPartResultTest, ResultAccessorsWork) { + const TestPartResult success(TestPartResult::kSuccess, + "file.cc", + 42, + "message"); + EXPECT_TRUE(success.passed()); + EXPECT_FALSE(success.failed()); + EXPECT_FALSE(success.nonfatally_failed()); + EXPECT_FALSE(success.fatally_failed()); + + const TestPartResult nonfatal_failure(TestPartResult::kNonFatalFailure, + "file.cc", + 42, + "message"); + EXPECT_FALSE(nonfatal_failure.passed()); + EXPECT_TRUE(nonfatal_failure.failed()); + EXPECT_TRUE(nonfatal_failure.nonfatally_failed()); + EXPECT_FALSE(nonfatal_failure.fatally_failed()); + + const TestPartResult fatal_failure(TestPartResult::kFatalFailure, + "file.cc", + 42, + "message"); + EXPECT_FALSE(fatal_failure.passed()); + EXPECT_TRUE(fatal_failure.failed()); + EXPECT_FALSE(fatal_failure.nonfatally_failed()); + EXPECT_TRUE(fatal_failure.fatally_failed()); +} + +// Tests TestPartResult::type(). +TEST_F(TestPartResultTest, type) { + EXPECT_EQ(TestPartResult::kSuccess, r1_.type()); + EXPECT_EQ(TestPartResult::kNonFatalFailure, r2_.type()); + EXPECT_EQ(TestPartResult::kFatalFailure, r3_.type()); +} + +// Tests TestPartResult::file_name(). +TEST_F(TestPartResultTest, file_name) { + EXPECT_STREQ("foo/bar.cc", r1_.file_name()); + EXPECT_STREQ(NULL, r3_.file_name()); +} + +// Tests TestPartResult::line_number(). +TEST_F(TestPartResultTest, line_number) { + EXPECT_EQ(10, r1_.line_number()); + EXPECT_EQ(-1, r2_.line_number()); +} + +// Tests TestPartResult::message(). +TEST_F(TestPartResultTest, message) { + EXPECT_STREQ("Success!", r1_.message()); +} + +// Tests TestPartResult::passed(). +TEST_F(TestPartResultTest, Passed) { + EXPECT_TRUE(r1_.passed()); + EXPECT_FALSE(r2_.passed()); + EXPECT_FALSE(r3_.passed()); +} + +// Tests TestPartResult::failed(). +TEST_F(TestPartResultTest, Failed) { + EXPECT_FALSE(r1_.failed()); + EXPECT_TRUE(r2_.failed()); + EXPECT_TRUE(r3_.failed()); +} + +// Tests TestPartResult::fatally_failed(). +TEST_F(TestPartResultTest, FatallyFailed) { + EXPECT_FALSE(r1_.fatally_failed()); + EXPECT_FALSE(r2_.fatally_failed()); + EXPECT_TRUE(r3_.fatally_failed()); +} + +// Tests TestPartResult::nonfatally_failed(). +TEST_F(TestPartResultTest, NonfatallyFailed) { + EXPECT_FALSE(r1_.nonfatally_failed()); + EXPECT_TRUE(r2_.nonfatally_failed()); + EXPECT_FALSE(r3_.nonfatally_failed()); +} + +// Tests the TestPartResultArray class. + +class TestPartResultArrayTest : public Test { + protected: + TestPartResultArrayTest() + : r1_(TestPartResult::kNonFatalFailure, "foo/bar.cc", -1, "Failure 1"), + r2_(TestPartResult::kFatalFailure, "foo/bar.cc", -1, "Failure 2") {} + + const TestPartResult r1_, r2_; +}; + +// Tests that TestPartResultArray initially has size 0. +TEST_F(TestPartResultArrayTest, InitialSizeIsZero) { + TestPartResultArray results; + EXPECT_EQ(0, results.size()); +} + +// Tests that TestPartResultArray contains the given TestPartResult +// after one Append() operation. +TEST_F(TestPartResultArrayTest, ContainsGivenResultAfterAppend) { + TestPartResultArray results; + results.Append(r1_); + EXPECT_EQ(1, results.size()); + EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message()); +} + +// Tests that TestPartResultArray contains the given TestPartResults +// after two Append() operations. +TEST_F(TestPartResultArrayTest, ContainsGivenResultsAfterTwoAppends) { + TestPartResultArray results; + results.Append(r1_); + results.Append(r2_); + EXPECT_EQ(2, results.size()); + EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message()); + EXPECT_STREQ("Failure 2", results.GetTestPartResult(1).message()); +} + +typedef TestPartResultArrayTest TestPartResultArrayDeathTest; + +// Tests that the program dies when GetTestPartResult() is called with +// an invalid index. +TEST_F(TestPartResultArrayDeathTest, DiesWhenIndexIsOutOfBound) { + TestPartResultArray results; + results.Append(r1_); + + EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(-1), ""); + EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(1), ""); +} + +// TODO(mheule@google.com): Add a test for the class HasNewFatalFailureHelper. + +} // namespace diff --git a/googletest/test/googletest-test2_test.cc b/googletest/test/googletest-test2_test.cc new file mode 100644 index 0000000..732e356 --- /dev/null +++ b/googletest/test/googletest-test2_test.cc @@ -0,0 +1,61 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: vladl@google.com (Vlad Losev) +// +// Tests for Google Test itself. This verifies that the basic constructs of +// Google Test work. + +#include "gtest/gtest.h" +#include "googletest-param-test-test.h" + +using ::testing::Values; +using ::testing::internal::ParamGenerator; + +// Tests that generators defined in a different translation unit +// are functional. The test using extern_gen_2 is defined +// in gtest-param-test_test.cc. +ParamGenerator extern_gen_2 = Values(33); + +// Tests that a parameterized test case can be defined in one translation unit +// and instantiated in another. The test is defined in gtest-param-test_test.cc +// and ExternalInstantiationTest fixture class is defined in +// gtest-param-test_test.h. +INSTANTIATE_TEST_CASE_P(MultiplesOf33, + ExternalInstantiationTest, + Values(33, 66)); + +// Tests that a parameterized test case can be instantiated +// in multiple translation units. Another instantiation is defined +// in gtest-param-test_test.cc and InstantiationInMultipleTranslaionUnitsTest +// fixture is defined in gtest-param-test_test.h +INSTANTIATE_TEST_CASE_P(Sequence2, + InstantiationInMultipleTranslaionUnitsTest, + Values(42*3, 42*4, 42*5)); + diff --git a/googletest/test/gtest-death-test_ex_test.cc b/googletest/test/gtest-death-test_ex_test.cc deleted file mode 100644 index b50a13d..0000000 --- a/googletest/test/gtest-death-test_ex_test.cc +++ /dev/null @@ -1,93 +0,0 @@ -// 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 that verify interaction of exceptions and death tests. - -#include "gtest/gtest-death-test.h" -#include "gtest/gtest.h" - -#if GTEST_HAS_DEATH_TEST - -# if GTEST_HAS_SEH -# include // For RaiseException(). -# endif - -# include "gtest/gtest-spi.h" - -# if GTEST_HAS_EXCEPTIONS - -# include // For std::exception. - -// Tests that death tests report thrown exceptions as failures and that the -// exceptions do not escape death test macros. -TEST(CxxExceptionDeathTest, ExceptionIsFailure) { - try { - EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw 1, ""), "threw an exception"); - } catch (...) { // NOLINT - FAIL() << "An exception escaped a death test macro invocation " - << "with catch_exceptions " - << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled"); - } -} - -class TestException : public std::exception { - public: - virtual const char* what() const throw() { return "exceptional message"; } -}; - -TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) { - // Verifies that the exception message is quoted in the failure text. - EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), - "exceptional message"); - // Verifies that the location is mentioned in the failure text. - EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), - "gtest-death-test_ex_test.cc"); -} -# endif // GTEST_HAS_EXCEPTIONS - -# if GTEST_HAS_SEH -// Tests that enabling interception of SEH exceptions with the -// catch_exceptions flag does not interfere with SEH exceptions being -// treated as death by death tests. -TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) { - EXPECT_DEATH(RaiseException(42, 0x0, 0, NULL), "") - << "with catch_exceptions " - << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled"); -} -# endif - -#endif // GTEST_HAS_DEATH_TEST - -int main(int argc, char** argv) { - testing::InitGoogleTest(&argc, argv); - testing::GTEST_FLAG(catch_exceptions) = GTEST_ENABLE_CATCH_EXCEPTIONS_ != 0; - return RUN_ALL_TESTS(); -} diff --git a/googletest/test/gtest-param-test2_test.cc b/googletest/test/gtest-param-test2_test.cc deleted file mode 100644 index c3b2d18..0000000 --- a/googletest/test/gtest-param-test2_test.cc +++ /dev/null @@ -1,61 +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. -// -// Author: vladl@google.com (Vlad Losev) -// -// Tests for Google Test itself. This verifies that the basic constructs of -// Google Test work. - -#include "gtest/gtest.h" -#include "gtest-param-test_test.h" - -using ::testing::Values; -using ::testing::internal::ParamGenerator; - -// Tests that generators defined in a different translation unit -// are functional. The test using extern_gen is defined -// in gtest-param-test_test.cc. -ParamGenerator extern_gen = Values(33); - -// Tests that a parameterized test case can be defined in one translation unit -// and instantiated in another. The test is defined in gtest-param-test_test.cc -// and ExternalInstantiationTest fixture class is defined in -// gtest-param-test_test.h. -INSTANTIATE_TEST_CASE_P(MultiplesOf33, - ExternalInstantiationTest, - Values(33, 66)); - -// Tests that a parameterized test case can be instantiated -// in multiple translation units. Another instantiation is defined -// in gtest-param-test_test.cc and InstantiationInMultipleTranslaionUnitsTest -// fixture is defined in gtest-param-test_test.h -INSTANTIATE_TEST_CASE_P(Sequence2, - InstantiationInMultipleTranslaionUnitsTest, - Values(42*3, 42*4, 42*5)); - diff --git a/googletest/test/gtest-param-test_test.cc b/googletest/test/gtest-param-test_test.cc deleted file mode 100644 index adc4d1b..0000000 --- a/googletest/test/gtest-param-test_test.cc +++ /dev/null @@ -1,1110 +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. -// -// Author: vladl@google.com (Vlad Losev) -// -// Tests for Google Test itself. This file verifies that the parameter -// generators objects produce correct parameter sequences and that -// Google Test runtime instantiates correct tests from those sequences. - -#include "gtest/gtest.h" - -# include -# include -# include -# include -# include -# include - -# include "src/gtest-internal-inl.h" // for UnitTestOptions -# include "test/gtest-param-test_test.h" - -using ::std::vector; -using ::std::sort; - -using ::testing::AddGlobalTestEnvironment; -using ::testing::Bool; -using ::testing::Message; -using ::testing::Range; -using ::testing::TestWithParam; -using ::testing::Values; -using ::testing::ValuesIn; - -# if GTEST_HAS_COMBINE -using ::testing::Combine; -using ::testing::get; -using ::testing::make_tuple; -using ::testing::tuple; -# endif // GTEST_HAS_COMBINE - -using ::testing::internal::ParamGenerator; -using ::testing::internal::UnitTestOptions; - -// Prints a value to a string. -// -// TODO(wan@google.com): remove PrintValue() when we move matchers and -// EXPECT_THAT() from Google Mock to Google Test. At that time, we -// can write EXPECT_THAT(x, Eq(y)) to compare two tuples x and y, as -// EXPECT_THAT() and the matchers know how to print tuples. -template -::std::string PrintValue(const T& value) { - ::std::stringstream stream; - stream << value; - return stream.str(); -} - -# if GTEST_HAS_COMBINE - -// These overloads allow printing tuples in our tests. We cannot -// define an operator<< for tuples, as that definition needs to be in -// the std namespace in order to be picked up by Google Test via -// Argument-Dependent Lookup, yet defining anything in the std -// namespace in non-STL code is undefined behavior. - -template -::std::string PrintValue(const tuple& value) { - ::std::stringstream stream; - stream << "(" << get<0>(value) << ", " << get<1>(value) << ")"; - return stream.str(); -} - -template -::std::string PrintValue(const tuple& value) { - ::std::stringstream stream; - stream << "(" << get<0>(value) << ", " << get<1>(value) - << ", "<< get<2>(value) << ")"; - return stream.str(); -} - -template -::std::string PrintValue( - const tuple& value) { - ::std::stringstream stream; - stream << "(" << get<0>(value) << ", " << get<1>(value) - << ", "<< get<2>(value) << ", " << get<3>(value) - << ", "<< get<4>(value) << ", " << get<5>(value) - << ", "<< get<6>(value) << ", " << get<7>(value) - << ", "<< get<8>(value) << ", " << get<9>(value) << ")"; - return stream.str(); -} - -# endif // GTEST_HAS_COMBINE - -// Verifies that a sequence generated by the generator and accessed -// via the iterator object matches the expected one using Google Test -// assertions. -template -void VerifyGenerator(const ParamGenerator& generator, - const T (&expected_values)[N]) { - typename ParamGenerator::iterator it = generator.begin(); - for (size_t i = 0; i < N; ++i) { - ASSERT_FALSE(it == generator.end()) - << "At element " << i << " when accessing via an iterator " - << "created with the copy constructor.\n"; - // We cannot use EXPECT_EQ() here as the values may be tuples, - // which don't support <<. - EXPECT_TRUE(expected_values[i] == *it) - << "where i is " << i - << ", expected_values[i] is " << PrintValue(expected_values[i]) - << ", *it is " << PrintValue(*it) - << ", and 'it' is an iterator created with the copy constructor.\n"; - ++it; - } - EXPECT_TRUE(it == generator.end()) - << "At the presumed end of sequence when accessing via an iterator " - << "created with the copy constructor.\n"; - - // Test the iterator assignment. The following lines verify that - // the sequence accessed via an iterator initialized via the - // assignment operator (as opposed to a copy constructor) matches - // just the same. - it = generator.begin(); - for (size_t i = 0; i < N; ++i) { - ASSERT_FALSE(it == generator.end()) - << "At element " << i << " when accessing via an iterator " - << "created with the assignment operator.\n"; - EXPECT_TRUE(expected_values[i] == *it) - << "where i is " << i - << ", expected_values[i] is " << PrintValue(expected_values[i]) - << ", *it is " << PrintValue(*it) - << ", and 'it' is an iterator created with the copy constructor.\n"; - ++it; - } - EXPECT_TRUE(it == generator.end()) - << "At the presumed end of sequence when accessing via an iterator " - << "created with the assignment operator.\n"; -} - -template -void VerifyGeneratorIsEmpty(const ParamGenerator& generator) { - typename ParamGenerator::iterator it = generator.begin(); - EXPECT_TRUE(it == generator.end()); - - it = generator.begin(); - EXPECT_TRUE(it == generator.end()); -} - -// Generator tests. They test that each of the provided generator functions -// generates an expected sequence of values. The general test pattern -// instantiates a generator using one of the generator functions, -// checks the sequence produced by the generator using its iterator API, -// and then resets the iterator back to the beginning of the sequence -// and checks the sequence again. - -// Tests that iterators produced by generator functions conform to the -// ForwardIterator concept. -TEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) { - const ParamGenerator gen = Range(0, 10); - ParamGenerator::iterator it = gen.begin(); - - // Verifies that iterator initialization works as expected. - ParamGenerator::iterator it2 = it; - EXPECT_TRUE(*it == *it2) << "Initialized iterators must point to the " - << "element same as its source points to"; - - // Verifies that iterator assignment works as expected. - ++it; - EXPECT_FALSE(*it == *it2); - it2 = it; - EXPECT_TRUE(*it == *it2) << "Assigned iterators must point to the " - << "element same as its source points to"; - - // Verifies that prefix operator++() returns *this. - EXPECT_EQ(&it, &(++it)) << "Result of the prefix operator++ must be " - << "refer to the original object"; - - // Verifies that the result of the postfix operator++ points to the value - // pointed to by the original iterator. - int original_value = *it; // Have to compute it outside of macro call to be - // unaffected by the parameter evaluation order. - EXPECT_EQ(original_value, *(it++)); - - // Verifies that prefix and postfix operator++() advance an iterator - // all the same. - it2 = it; - ++it; - ++it2; - EXPECT_TRUE(*it == *it2); -} - -// Tests that Range() generates the expected sequence. -TEST(RangeTest, IntRangeWithDefaultStep) { - const ParamGenerator gen = Range(0, 3); - const int expected_values[] = {0, 1, 2}; - VerifyGenerator(gen, expected_values); -} - -// Edge case. Tests that Range() generates the single element sequence -// as expected when provided with range limits that are equal. -TEST(RangeTest, IntRangeSingleValue) { - const ParamGenerator gen = Range(0, 1); - const int expected_values[] = {0}; - VerifyGenerator(gen, expected_values); -} - -// Edge case. Tests that Range() with generates empty sequence when -// supplied with an empty range. -TEST(RangeTest, IntRangeEmpty) { - const ParamGenerator gen = Range(0, 0); - VerifyGeneratorIsEmpty(gen); -} - -// Tests that Range() with custom step (greater then one) generates -// the expected sequence. -TEST(RangeTest, IntRangeWithCustomStep) { - const ParamGenerator gen = Range(0, 9, 3); - const int expected_values[] = {0, 3, 6}; - VerifyGenerator(gen, expected_values); -} - -// Tests that Range() with custom step (greater then one) generates -// the expected sequence when the last element does not fall on the -// upper range limit. Sequences generated by Range() must not have -// elements beyond the range limits. -TEST(RangeTest, IntRangeWithCustomStepOverUpperBound) { - const ParamGenerator gen = Range(0, 4, 3); - const int expected_values[] = {0, 3}; - VerifyGenerator(gen, expected_values); -} - -// Verifies that Range works with user-defined types that define -// copy constructor, operator=(), operator+(), and operator<(). -class DogAdder { - public: - explicit DogAdder(const char* a_value) : value_(a_value) {} - DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {} - - DogAdder operator=(const DogAdder& other) { - if (this != &other) - value_ = other.value_; - return *this; - } - DogAdder operator+(const DogAdder& other) const { - Message msg; - msg << value_.c_str() << other.value_.c_str(); - return DogAdder(msg.GetString().c_str()); - } - bool operator<(const DogAdder& other) const { - return value_ < other.value_; - } - const std::string& value() const { return value_; } - - private: - std::string value_; -}; - -TEST(RangeTest, WorksWithACustomType) { - const ParamGenerator gen = - Range(DogAdder("cat"), DogAdder("catdogdog"), DogAdder("dog")); - ParamGenerator::iterator it = gen.begin(); - - ASSERT_FALSE(it == gen.end()); - EXPECT_STREQ("cat", it->value().c_str()); - - ASSERT_FALSE(++it == gen.end()); - EXPECT_STREQ("catdog", it->value().c_str()); - - EXPECT_TRUE(++it == gen.end()); -} - -class IntWrapper { - public: - explicit IntWrapper(int a_value) : value_(a_value) {} - IntWrapper(const IntWrapper& other) : value_(other.value_) {} - - IntWrapper operator=(const IntWrapper& other) { - value_ = other.value_; - return *this; - } - // operator+() adds a different type. - IntWrapper operator+(int other) const { return IntWrapper(value_ + other); } - bool operator<(const IntWrapper& other) const { - return value_ < other.value_; - } - int value() const { return value_; } - - private: - int value_; -}; - -TEST(RangeTest, WorksWithACustomTypeWithDifferentIncrementType) { - const ParamGenerator gen = Range(IntWrapper(0), IntWrapper(2)); - ParamGenerator::iterator it = gen.begin(); - - ASSERT_FALSE(it == gen.end()); - EXPECT_EQ(0, it->value()); - - ASSERT_FALSE(++it == gen.end()); - EXPECT_EQ(1, it->value()); - - EXPECT_TRUE(++it == gen.end()); -} - -// Tests that ValuesIn() with an array parameter generates -// the expected sequence. -TEST(ValuesInTest, ValuesInArray) { - int array[] = {3, 5, 8}; - const ParamGenerator gen = ValuesIn(array); - VerifyGenerator(gen, array); -} - -// Tests that ValuesIn() with a const array parameter generates -// the expected sequence. -TEST(ValuesInTest, ValuesInConstArray) { - const int array[] = {3, 5, 8}; - const ParamGenerator gen = ValuesIn(array); - VerifyGenerator(gen, array); -} - -// Edge case. Tests that ValuesIn() with an array parameter containing a -// single element generates the single element sequence. -TEST(ValuesInTest, ValuesInSingleElementArray) { - int array[] = {42}; - const ParamGenerator gen = ValuesIn(array); - VerifyGenerator(gen, array); -} - -// Tests that ValuesIn() generates the expected sequence for an STL -// container (vector). -TEST(ValuesInTest, ValuesInVector) { - typedef ::std::vector ContainerType; - ContainerType values; - values.push_back(3); - values.push_back(5); - values.push_back(8); - const ParamGenerator gen = ValuesIn(values); - - const int expected_values[] = {3, 5, 8}; - VerifyGenerator(gen, expected_values); -} - -// Tests that ValuesIn() generates the expected sequence. -TEST(ValuesInTest, ValuesInIteratorRange) { - typedef ::std::vector ContainerType; - ContainerType values; - values.push_back(3); - values.push_back(5); - values.push_back(8); - const ParamGenerator gen = ValuesIn(values.begin(), values.end()); - - const int expected_values[] = {3, 5, 8}; - VerifyGenerator(gen, expected_values); -} - -// Edge case. Tests that ValuesIn() provided with an iterator range specifying a -// single value generates a single-element sequence. -TEST(ValuesInTest, ValuesInSingleElementIteratorRange) { - typedef ::std::vector ContainerType; - ContainerType values; - values.push_back(42); - const ParamGenerator gen = ValuesIn(values.begin(), values.end()); - - const int expected_values[] = {42}; - VerifyGenerator(gen, expected_values); -} - -// Edge case. Tests that ValuesIn() provided with an empty iterator range -// generates an empty sequence. -TEST(ValuesInTest, ValuesInEmptyIteratorRange) { - typedef ::std::vector ContainerType; - ContainerType values; - const ParamGenerator gen = ValuesIn(values.begin(), values.end()); - - VerifyGeneratorIsEmpty(gen); -} - -// Tests that the Values() generates the expected sequence. -TEST(ValuesTest, ValuesWorks) { - const ParamGenerator gen = Values(3, 5, 8); - - const int expected_values[] = {3, 5, 8}; - VerifyGenerator(gen, expected_values); -} - -// Tests that Values() generates the expected sequences from elements of -// different types convertible to ParamGenerator's parameter type. -TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) { - const ParamGenerator gen = Values(3, 5.0f, 8.0); - - const double expected_values[] = {3.0, 5.0, 8.0}; - VerifyGenerator(gen, expected_values); -} - -TEST(ValuesTest, ValuesWorksForMaxLengthList) { - const ParamGenerator gen = Values( - 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, - 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, - 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, - 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, - 410, 420, 430, 440, 450, 460, 470, 480, 490, 500); - - const int expected_values[] = { - 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, - 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, - 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, - 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, - 410, 420, 430, 440, 450, 460, 470, 480, 490, 500}; - VerifyGenerator(gen, expected_values); -} - -// Edge case test. Tests that single-parameter Values() generates the sequence -// with the single value. -TEST(ValuesTest, ValuesWithSingleParameter) { - const ParamGenerator gen = Values(42); - - const int expected_values[] = {42}; - VerifyGenerator(gen, expected_values); -} - -// Tests that Bool() generates sequence (false, true). -TEST(BoolTest, BoolWorks) { - const ParamGenerator gen = Bool(); - - const bool expected_values[] = {false, true}; - VerifyGenerator(gen, expected_values); -} - -# if GTEST_HAS_COMBINE - -// Tests that Combine() with two parameters generates the expected sequence. -TEST(CombineTest, CombineWithTwoParameters) { - const char* foo = "foo"; - const char* bar = "bar"; - const ParamGenerator > gen = - Combine(Values(foo, bar), Values(3, 4)); - - tuple expected_values[] = { - make_tuple(foo, 3), make_tuple(foo, 4), - make_tuple(bar, 3), make_tuple(bar, 4)}; - VerifyGenerator(gen, expected_values); -} - -// Tests that Combine() with three parameters generates the expected sequence. -TEST(CombineTest, CombineWithThreeParameters) { - const ParamGenerator > gen = Combine(Values(0, 1), - Values(3, 4), - Values(5, 6)); - tuple expected_values[] = { - make_tuple(0, 3, 5), make_tuple(0, 3, 6), - make_tuple(0, 4, 5), make_tuple(0, 4, 6), - make_tuple(1, 3, 5), make_tuple(1, 3, 6), - make_tuple(1, 4, 5), make_tuple(1, 4, 6)}; - VerifyGenerator(gen, expected_values); -} - -// Tests that the Combine() with the first parameter generating a single value -// sequence generates a sequence with the number of elements equal to the -// number of elements in the sequence generated by the second parameter. -TEST(CombineTest, CombineWithFirstParameterSingleValue) { - const ParamGenerator > gen = Combine(Values(42), - Values(0, 1)); - - tuple expected_values[] = {make_tuple(42, 0), make_tuple(42, 1)}; - VerifyGenerator(gen, expected_values); -} - -// Tests that the Combine() with the second parameter generating a single value -// sequence generates a sequence with the number of elements equal to the -// number of elements in the sequence generated by the first parameter. -TEST(CombineTest, CombineWithSecondParameterSingleValue) { - const ParamGenerator > gen = Combine(Values(0, 1), - Values(42)); - - tuple expected_values[] = {make_tuple(0, 42), make_tuple(1, 42)}; - VerifyGenerator(gen, expected_values); -} - -// Tests that when the first parameter produces an empty sequence, -// Combine() produces an empty sequence, too. -TEST(CombineTest, CombineWithFirstParameterEmptyRange) { - const ParamGenerator > gen = Combine(Range(0, 0), - Values(0, 1)); - VerifyGeneratorIsEmpty(gen); -} - -// Tests that when the second parameter produces an empty sequence, -// Combine() produces an empty sequence, too. -TEST(CombineTest, CombineWithSecondParameterEmptyRange) { - const ParamGenerator > gen = Combine(Values(0, 1), - Range(1, 1)); - VerifyGeneratorIsEmpty(gen); -} - -// Edge case. Tests that combine works with the maximum number -// of parameters supported by Google Test (currently 10). -TEST(CombineTest, CombineWithMaxNumberOfParameters) { - const char* foo = "foo"; - const char* bar = "bar"; - const ParamGenerator > gen = Combine(Values(foo, bar), - Values(1), Values(2), - Values(3), Values(4), - Values(5), Values(6), - Values(7), Values(8), - Values(9)); - - tuple - expected_values[] = {make_tuple(foo, 1, 2, 3, 4, 5, 6, 7, 8, 9), - make_tuple(bar, 1, 2, 3, 4, 5, 6, 7, 8, 9)}; - VerifyGenerator(gen, expected_values); -} - -#if GTEST_LANG_CXX11 - -class NonDefaultConstructAssignString { - public: - NonDefaultConstructAssignString(const std::string& s) : str_(s) {} - - const std::string& str() const { return str_; } - - private: - std::string str_; - - // Not default constructible - NonDefaultConstructAssignString(); - // Not assignable - void operator=(const NonDefaultConstructAssignString&); -}; - -TEST(CombineTest, NonDefaultConstructAssign) { - const ParamGenerator > gen = - Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"), - NonDefaultConstructAssignString("B"))); - - ParamGenerator >::iterator it = - gen.begin(); - - EXPECT_EQ(0, std::get<0>(*it)); - EXPECT_EQ("A", std::get<1>(*it).str()); - ++it; - - EXPECT_EQ(0, std::get<0>(*it)); - EXPECT_EQ("B", std::get<1>(*it).str()); - ++it; - - EXPECT_EQ(1, std::get<0>(*it)); - EXPECT_EQ("A", std::get<1>(*it).str()); - ++it; - - EXPECT_EQ(1, std::get<0>(*it)); - EXPECT_EQ("B", std::get<1>(*it).str()); - ++it; - - EXPECT_TRUE(it == gen.end()); -} - -#endif // GTEST_LANG_CXX11 -# endif // GTEST_HAS_COMBINE - -// Tests that an generator produces correct sequence after being -// assigned from another generator. -TEST(ParamGeneratorTest, AssignmentWorks) { - ParamGenerator gen = Values(1, 2); - const ParamGenerator gen2 = Values(3, 4); - gen = gen2; - - const int expected_values[] = {3, 4}; - VerifyGenerator(gen, expected_values); -} - -// This test verifies that the tests are expanded and run as specified: -// one test per element from the sequence produced by the generator -// specified in INSTANTIATE_TEST_CASE_P. It also verifies that the test's -// fixture constructor, SetUp(), and TearDown() have run and have been -// supplied with the correct parameters. - -// The use of environment object allows detection of the case where no test -// case functionality is run at all. In this case TestCaseTearDown will not -// be able to detect missing tests, naturally. -template -class TestGenerationEnvironment : public ::testing::Environment { - public: - static TestGenerationEnvironment* Instance() { - static TestGenerationEnvironment* instance = new TestGenerationEnvironment; - return instance; - } - - void FixtureConstructorExecuted() { fixture_constructor_count_++; } - void SetUpExecuted() { set_up_count_++; } - void TearDownExecuted() { tear_down_count_++; } - void TestBodyExecuted() { test_body_count_++; } - - virtual void TearDown() { - // If all MultipleTestGenerationTest tests have been de-selected - // by the filter flag, the following checks make no sense. - bool perform_check = false; - - for (int i = 0; i < kExpectedCalls; ++i) { - Message msg; - msg << "TestsExpandedAndRun/" << i; - if (UnitTestOptions::FilterMatchesTest( - "TestExpansionModule/MultipleTestGenerationTest", - msg.GetString().c_str())) { - perform_check = true; - } - } - if (perform_check) { - EXPECT_EQ(kExpectedCalls, fixture_constructor_count_) - << "Fixture constructor of ParamTestGenerationTest test case " - << "has not been run as expected."; - EXPECT_EQ(kExpectedCalls, set_up_count_) - << "Fixture SetUp method of ParamTestGenerationTest test case " - << "has not been run as expected."; - EXPECT_EQ(kExpectedCalls, tear_down_count_) - << "Fixture TearDown method of ParamTestGenerationTest test case " - << "has not been run as expected."; - EXPECT_EQ(kExpectedCalls, test_body_count_) - << "Test in ParamTestGenerationTest test case " - << "has not been run as expected."; - } - } - - private: - TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0), - tear_down_count_(0), test_body_count_(0) {} - - int fixture_constructor_count_; - int set_up_count_; - int tear_down_count_; - int test_body_count_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationEnvironment); -}; - -const int test_generation_params[] = {36, 42, 72}; - -class TestGenerationTest : public TestWithParam { - public: - enum { - PARAMETER_COUNT = - sizeof(test_generation_params)/sizeof(test_generation_params[0]) - }; - - typedef TestGenerationEnvironment Environment; - - TestGenerationTest() { - Environment::Instance()->FixtureConstructorExecuted(); - current_parameter_ = GetParam(); - } - virtual void SetUp() { - Environment::Instance()->SetUpExecuted(); - EXPECT_EQ(current_parameter_, GetParam()); - } - virtual void TearDown() { - Environment::Instance()->TearDownExecuted(); - EXPECT_EQ(current_parameter_, GetParam()); - } - - static void SetUpTestCase() { - bool all_tests_in_test_case_selected = true; - - for (int i = 0; i < PARAMETER_COUNT; ++i) { - Message test_name; - test_name << "TestsExpandedAndRun/" << i; - if ( !UnitTestOptions::FilterMatchesTest( - "TestExpansionModule/MultipleTestGenerationTest", - test_name.GetString())) { - all_tests_in_test_case_selected = false; - } - } - EXPECT_TRUE(all_tests_in_test_case_selected) - << "When running the TestGenerationTest test case all of its tests\n" - << "must be selected by the filter flag for the test case to pass.\n" - << "If not all of them are enabled, we can't reliably conclude\n" - << "that the correct number of tests have been generated."; - - collected_parameters_.clear(); - } - - static void TearDownTestCase() { - vector expected_values(test_generation_params, - test_generation_params + PARAMETER_COUNT); - // Test execution order is not guaranteed by Google Test, - // so the order of values in collected_parameters_ can be - // different and we have to sort to compare. - sort(expected_values.begin(), expected_values.end()); - sort(collected_parameters_.begin(), collected_parameters_.end()); - - EXPECT_TRUE(collected_parameters_ == expected_values); - } - - protected: - int current_parameter_; - static vector collected_parameters_; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationTest); -}; -vector TestGenerationTest::collected_parameters_; - -TEST_P(TestGenerationTest, TestsExpandedAndRun) { - Environment::Instance()->TestBodyExecuted(); - EXPECT_EQ(current_parameter_, GetParam()); - collected_parameters_.push_back(GetParam()); -} -INSTANTIATE_TEST_CASE_P(TestExpansionModule, TestGenerationTest, - ValuesIn(test_generation_params)); - -// This test verifies that the element sequence (third parameter of -// INSTANTIATE_TEST_CASE_P) is evaluated in InitGoogleTest() and neither at -// the call site of INSTANTIATE_TEST_CASE_P nor in RUN_ALL_TESTS(). For -// that, we declare param_value_ to be a static member of -// GeneratorEvaluationTest and initialize it to 0. We set it to 1 in -// main(), just before invocation of InitGoogleTest(). After calling -// InitGoogleTest(), we set the value to 2. If the sequence is evaluated -// before or after InitGoogleTest, INSTANTIATE_TEST_CASE_P will create a -// test with parameter other than 1, and the test body will fail the -// assertion. -class GeneratorEvaluationTest : public TestWithParam { - public: - static int param_value() { return param_value_; } - static void set_param_value(int param_value) { param_value_ = param_value; } - - private: - static int param_value_; -}; -int GeneratorEvaluationTest::param_value_ = 0; - -TEST_P(GeneratorEvaluationTest, GeneratorsEvaluatedInMain) { - EXPECT_EQ(1, GetParam()); -} -INSTANTIATE_TEST_CASE_P(GenEvalModule, - GeneratorEvaluationTest, - Values(GeneratorEvaluationTest::param_value())); - -// Tests that generators defined in a different translation unit are -// functional. Generator extern_gen is defined in gtest-param-test_test2.cc. -extern ParamGenerator extern_gen; -class ExternalGeneratorTest : public TestWithParam {}; -TEST_P(ExternalGeneratorTest, ExternalGenerator) { - // Sequence produced by extern_gen contains only a single value - // which we verify here. - EXPECT_EQ(GetParam(), 33); -} -INSTANTIATE_TEST_CASE_P(ExternalGeneratorModule, - ExternalGeneratorTest, - extern_gen); - -// Tests that a parameterized test case can be defined in one translation -// unit and instantiated in another. This test will be instantiated in -// gtest-param-test_test2.cc. ExternalInstantiationTest fixture class is -// defined in gtest-param-test_test.h. -TEST_P(ExternalInstantiationTest, IsMultipleOf33) { - EXPECT_EQ(0, GetParam() % 33); -} - -// Tests that a parameterized test case can be instantiated with multiple -// generators. -class MultipleInstantiationTest : public TestWithParam {}; -TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) { -} -INSTANTIATE_TEST_CASE_P(Sequence1, MultipleInstantiationTest, Values(1, 2)); -INSTANTIATE_TEST_CASE_P(Sequence2, MultipleInstantiationTest, Range(3, 5)); - -// Tests that a parameterized test case can be instantiated -// in multiple translation units. This test will be instantiated -// here and in gtest-param-test_test2.cc. -// InstantiationInMultipleTranslationUnitsTest fixture class -// is defined in gtest-param-test_test.h. -TEST_P(InstantiationInMultipleTranslaionUnitsTest, IsMultipleOf42) { - EXPECT_EQ(0, GetParam() % 42); -} -INSTANTIATE_TEST_CASE_P(Sequence1, - InstantiationInMultipleTranslaionUnitsTest, - Values(42, 42*2)); - -// Tests that each iteration of parameterized test runs in a separate test -// object. -class SeparateInstanceTest : public TestWithParam { - public: - SeparateInstanceTest() : count_(0) {} - - static void TearDownTestCase() { - EXPECT_GE(global_count_, 2) - << "If some (but not all) SeparateInstanceTest tests have been " - << "filtered out this test will fail. Make sure that all " - << "GeneratorEvaluationTest are selected or de-selected together " - << "by the test filter."; - } - - protected: - int count_; - static int global_count_; -}; -int SeparateInstanceTest::global_count_ = 0; - -TEST_P(SeparateInstanceTest, TestsRunInSeparateInstances) { - EXPECT_EQ(0, count_++); - global_count_++; -} -INSTANTIATE_TEST_CASE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4)); - -// Tests that all instantiations of a test have named appropriately. Test -// defined with TEST_P(TestCaseName, TestName) and instantiated with -// INSTANTIATE_TEST_CASE_P(SequenceName, TestCaseName, generator) must be named -// SequenceName/TestCaseName.TestName/i, where i is the 0-based index of the -// sequence element used to instantiate the test. -class NamingTest : public TestWithParam {}; - -TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - - EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_case_name()); - - Message index_stream; - index_stream << "TestsReportCorrectNamesAndParameters/" << GetParam(); - EXPECT_STREQ(index_stream.GetString().c_str(), test_info->name()); - - EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param()); -} - -INSTANTIATE_TEST_CASE_P(ZeroToFiveSequence, NamingTest, Range(0, 5)); - -// Tests that macros in test names are expanded correctly. -class MacroNamingTest : public TestWithParam {}; - -#define PREFIX_WITH_FOO(test_name) Foo##test_name -#define PREFIX_WITH_MACRO(test_name) Macro##test_name - -TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - - EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_case_name()); - EXPECT_STREQ("FooSomeTestName", test_info->name()); -} - -INSTANTIATE_TEST_CASE_P(FortyTwo, MacroNamingTest, Values(42)); - -// Tests the same thing for non-parametrized tests. -class MacroNamingTestNonParametrized : public ::testing::Test {}; - -TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized), - PREFIX_WITH_FOO(SomeTestName)) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - - EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_case_name()); - EXPECT_STREQ("FooSomeTestName", test_info->name()); -} - -// Tests that user supplied custom parameter names are working correctly. -// Runs the test with a builtin helper method which uses PrintToString, -// as well as a custom function and custom functor to ensure all possible -// uses work correctly. -class CustomFunctorNamingTest : public TestWithParam {}; -TEST_P(CustomFunctorNamingTest, CustomTestNames) {} - -struct CustomParamNameFunctor { - std::string operator()(const ::testing::TestParamInfo& inf) { - return inf.param; - } -}; - -INSTANTIATE_TEST_CASE_P(CustomParamNameFunctor, - CustomFunctorNamingTest, - Values(std::string("FunctorName")), - CustomParamNameFunctor()); - -INSTANTIATE_TEST_CASE_P(AllAllowedCharacters, - CustomFunctorNamingTest, - Values("abcdefghijklmnopqrstuvwxyz", - "ABCDEFGHIJKLMNOPQRSTUVWXYZ", - "01234567890_"), - CustomParamNameFunctor()); - -inline std::string CustomParamNameFunction( - const ::testing::TestParamInfo& inf) { - return inf.param; -} - -class CustomFunctionNamingTest : public TestWithParam {}; -TEST_P(CustomFunctionNamingTest, CustomTestNames) {} - -INSTANTIATE_TEST_CASE_P(CustomParamNameFunction, - CustomFunctionNamingTest, - Values(std::string("FunctionName")), - CustomParamNameFunction); - -#if GTEST_LANG_CXX11 - -// Test custom naming with a lambda - -class CustomLambdaNamingTest : public TestWithParam {}; -TEST_P(CustomLambdaNamingTest, CustomTestNames) {} - -INSTANTIATE_TEST_CASE_P(CustomParamNameLambda, CustomLambdaNamingTest, - Values(std::string("LambdaName")), - [](const ::testing::TestParamInfo& inf) { - return inf.param; - }); - -#endif // GTEST_LANG_CXX11 - -TEST(CustomNamingTest, CheckNameRegistry) { - ::testing::UnitTest* unit_test = ::testing::UnitTest::GetInstance(); - std::set test_names; - for (int case_num = 0; - case_num < unit_test->total_test_case_count(); - ++case_num) { - const ::testing::TestCase* test_case = unit_test->GetTestCase(case_num); - for (int test_num = 0; - test_num < test_case->total_test_count(); - ++test_num) { - const ::testing::TestInfo* test_info = test_case->GetTestInfo(test_num); - test_names.insert(std::string(test_info->name())); - } - } - EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctorName")); - EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctionName")); -#if GTEST_LANG_CXX11 - EXPECT_EQ(1u, test_names.count("CustomTestNames/LambdaName")); -#endif // GTEST_LANG_CXX11 -} - -// Test a numeric name to ensure PrintToStringParamName works correctly. - -class CustomIntegerNamingTest : public TestWithParam {}; - -TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - Message test_name_stream; - test_name_stream << "TestsReportCorrectNames/" << GetParam(); - EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); -} - -INSTANTIATE_TEST_CASE_P(PrintToString, - CustomIntegerNamingTest, - Range(0, 5), - ::testing::PrintToStringParamName()); - -// Test a custom struct with PrintToString. - -struct CustomStruct { - explicit CustomStruct(int value) : x(value) {} - int x; -}; - -std::ostream& operator<<(std::ostream& stream, const CustomStruct& val) { - stream << val.x; - return stream; -} - -class CustomStructNamingTest : public TestWithParam {}; - -TEST_P(CustomStructNamingTest, TestsReportCorrectNames) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - Message test_name_stream; - test_name_stream << "TestsReportCorrectNames/" << GetParam(); - EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); -} - -INSTANTIATE_TEST_CASE_P(PrintToString, - CustomStructNamingTest, - Values(CustomStruct(0), CustomStruct(1)), - ::testing::PrintToStringParamName()); - -// Test that using a stateful parameter naming function works as expected. - -struct StatefulNamingFunctor { - StatefulNamingFunctor() : sum(0) {} - std::string operator()(const ::testing::TestParamInfo& info) { - int value = info.param + sum; - sum += info.param; - return ::testing::PrintToString(value); - } - int sum; -}; - -class StatefulNamingTest : public ::testing::TestWithParam { - protected: - StatefulNamingTest() : sum_(0) {} - int sum_; -}; - -TEST_P(StatefulNamingTest, TestsReportCorrectNames) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - sum_ += GetParam(); - Message test_name_stream; - test_name_stream << "TestsReportCorrectNames/" << sum_; - EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); -} - -INSTANTIATE_TEST_CASE_P(StatefulNamingFunctor, - StatefulNamingTest, - Range(0, 5), - StatefulNamingFunctor()); - -// Class that cannot be streamed into an ostream. It needs to be copyable -// (and, in case of MSVC, also assignable) in order to be a test parameter -// type. Its default copy constructor and assignment operator do exactly -// what we need. -class Unstreamable { - public: - explicit Unstreamable(int value) : value_(value) {} - - private: - int value_; -}; - -class CommentTest : public TestWithParam {}; - -TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - - EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param()); -} - -INSTANTIATE_TEST_CASE_P(InstantiationWithComments, - CommentTest, - Values(Unstreamable(1))); - -// Verify that we can create a hierarchy of test fixtures, where the base -// class fixture is not parameterized and the derived class is. In this case -// ParameterizedDerivedTest inherits from NonParameterizedBaseTest. We -// perform simple tests on both. -class NonParameterizedBaseTest : public ::testing::Test { - public: - NonParameterizedBaseTest() : n_(17) { } - protected: - int n_; -}; - -class ParameterizedDerivedTest : public NonParameterizedBaseTest, - public ::testing::WithParamInterface { - protected: - ParameterizedDerivedTest() : count_(0) { } - int count_; - static int global_count_; -}; - -int ParameterizedDerivedTest::global_count_ = 0; - -TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { - EXPECT_EQ(17, n_); -} - -TEST_P(ParameterizedDerivedTest, SeesSequence) { - EXPECT_EQ(17, n_); - EXPECT_EQ(0, count_++); - EXPECT_EQ(GetParam(), global_count_++); -} - -class ParameterizedDeathTest : public ::testing::TestWithParam { }; - -TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) { - EXPECT_DEATH_IF_SUPPORTED(GetParam(), - ".* value-parameterized test .*"); -} - -INSTANTIATE_TEST_CASE_P(RangeZeroToFive, ParameterizedDerivedTest, Range(0, 5)); - - -int main(int argc, char **argv) { - // Used in TestGenerationTest test case. - AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance()); - // Used in GeneratorEvaluationTest test case. Tests that the updated value - // will be picked up for instantiating tests in GeneratorEvaluationTest. - GeneratorEvaluationTest::set_param_value(1); - - ::testing::InitGoogleTest(&argc, argv); - - // Used in GeneratorEvaluationTest test case. Tests that value updated - // here will NOT be used for instantiating tests in - // GeneratorEvaluationTest. - GeneratorEvaluationTest::set_param_value(2); - - return RUN_ALL_TESTS(); -} diff --git a/googletest/test/gtest-param-test_test.h b/googletest/test/gtest-param-test_test.h deleted file mode 100644 index ea1e884..0000000 --- a/googletest/test/gtest-param-test_test.h +++ /dev/null @@ -1,53 +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. -// -// Authors: vladl@google.com (Vlad Losev) -// -// The Google C++ Testing and Mocking Framework (Google Test) -// -// This header file provides classes and functions used internally -// for testing Google Test itself. - -#ifndef GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ -#define GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ - -#include "gtest/gtest.h" - -// Test fixture for testing definition and instantiation of a test -// in separate translation units. -class ExternalInstantiationTest : public ::testing::TestWithParam { -}; - -// Test fixture for testing instantiation of a test in multiple -// translation units. -class InstantiationInMultipleTranslaionUnitsTest - : public ::testing::TestWithParam { -}; - -#endif // GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ diff --git a/googletest/test/gtest-test-part_test.cc b/googletest/test/gtest-test-part_test.cc deleted file mode 100644 index ca8ba93..0000000 --- a/googletest/test/gtest-test-part_test.cc +++ /dev/null @@ -1,208 +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. -// -// Author: mheule@google.com (Markus Heule) -// - -#include "gtest/gtest-test-part.h" - -#include "gtest/gtest.h" - -using testing::Message; -using testing::Test; -using testing::TestPartResult; -using testing::TestPartResultArray; - -namespace { - -// Tests the TestPartResult class. - -// The test fixture for testing TestPartResult. -class TestPartResultTest : public Test { - protected: - TestPartResultTest() - : r1_(TestPartResult::kSuccess, "foo/bar.cc", 10, "Success!"), - r2_(TestPartResult::kNonFatalFailure, "foo/bar.cc", -1, "Failure!"), - r3_(TestPartResult::kFatalFailure, NULL, -1, "Failure!") {} - - TestPartResult r1_, r2_, r3_; -}; - - -TEST_F(TestPartResultTest, ConstructorWorks) { - Message message; - message << "something is terribly wrong"; - message << static_cast(testing::internal::kStackTraceMarker); - message << "some unimportant stack trace"; - - const TestPartResult result(TestPartResult::kNonFatalFailure, - "some_file.cc", - 42, - message.GetString().c_str()); - - EXPECT_EQ(TestPartResult::kNonFatalFailure, result.type()); - EXPECT_STREQ("some_file.cc", result.file_name()); - EXPECT_EQ(42, result.line_number()); - EXPECT_STREQ(message.GetString().c_str(), result.message()); - EXPECT_STREQ("something is terribly wrong", result.summary()); -} - -TEST_F(TestPartResultTest, ResultAccessorsWork) { - const TestPartResult success(TestPartResult::kSuccess, - "file.cc", - 42, - "message"); - EXPECT_TRUE(success.passed()); - EXPECT_FALSE(success.failed()); - EXPECT_FALSE(success.nonfatally_failed()); - EXPECT_FALSE(success.fatally_failed()); - - const TestPartResult nonfatal_failure(TestPartResult::kNonFatalFailure, - "file.cc", - 42, - "message"); - EXPECT_FALSE(nonfatal_failure.passed()); - EXPECT_TRUE(nonfatal_failure.failed()); - EXPECT_TRUE(nonfatal_failure.nonfatally_failed()); - EXPECT_FALSE(nonfatal_failure.fatally_failed()); - - const TestPartResult fatal_failure(TestPartResult::kFatalFailure, - "file.cc", - 42, - "message"); - EXPECT_FALSE(fatal_failure.passed()); - EXPECT_TRUE(fatal_failure.failed()); - EXPECT_FALSE(fatal_failure.nonfatally_failed()); - EXPECT_TRUE(fatal_failure.fatally_failed()); -} - -// Tests TestPartResult::type(). -TEST_F(TestPartResultTest, type) { - EXPECT_EQ(TestPartResult::kSuccess, r1_.type()); - EXPECT_EQ(TestPartResult::kNonFatalFailure, r2_.type()); - EXPECT_EQ(TestPartResult::kFatalFailure, r3_.type()); -} - -// Tests TestPartResult::file_name(). -TEST_F(TestPartResultTest, file_name) { - EXPECT_STREQ("foo/bar.cc", r1_.file_name()); - EXPECT_STREQ(NULL, r3_.file_name()); -} - -// Tests TestPartResult::line_number(). -TEST_F(TestPartResultTest, line_number) { - EXPECT_EQ(10, r1_.line_number()); - EXPECT_EQ(-1, r2_.line_number()); -} - -// Tests TestPartResult::message(). -TEST_F(TestPartResultTest, message) { - EXPECT_STREQ("Success!", r1_.message()); -} - -// Tests TestPartResult::passed(). -TEST_F(TestPartResultTest, Passed) { - EXPECT_TRUE(r1_.passed()); - EXPECT_FALSE(r2_.passed()); - EXPECT_FALSE(r3_.passed()); -} - -// Tests TestPartResult::failed(). -TEST_F(TestPartResultTest, Failed) { - EXPECT_FALSE(r1_.failed()); - EXPECT_TRUE(r2_.failed()); - EXPECT_TRUE(r3_.failed()); -} - -// Tests TestPartResult::fatally_failed(). -TEST_F(TestPartResultTest, FatallyFailed) { - EXPECT_FALSE(r1_.fatally_failed()); - EXPECT_FALSE(r2_.fatally_failed()); - EXPECT_TRUE(r3_.fatally_failed()); -} - -// Tests TestPartResult::nonfatally_failed(). -TEST_F(TestPartResultTest, NonfatallyFailed) { - EXPECT_FALSE(r1_.nonfatally_failed()); - EXPECT_TRUE(r2_.nonfatally_failed()); - EXPECT_FALSE(r3_.nonfatally_failed()); -} - -// Tests the TestPartResultArray class. - -class TestPartResultArrayTest : public Test { - protected: - TestPartResultArrayTest() - : r1_(TestPartResult::kNonFatalFailure, "foo/bar.cc", -1, "Failure 1"), - r2_(TestPartResult::kFatalFailure, "foo/bar.cc", -1, "Failure 2") {} - - const TestPartResult r1_, r2_; -}; - -// Tests that TestPartResultArray initially has size 0. -TEST_F(TestPartResultArrayTest, InitialSizeIsZero) { - TestPartResultArray results; - EXPECT_EQ(0, results.size()); -} - -// Tests that TestPartResultArray contains the given TestPartResult -// after one Append() operation. -TEST_F(TestPartResultArrayTest, ContainsGivenResultAfterAppend) { - TestPartResultArray results; - results.Append(r1_); - EXPECT_EQ(1, results.size()); - EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message()); -} - -// Tests that TestPartResultArray contains the given TestPartResults -// after two Append() operations. -TEST_F(TestPartResultArrayTest, ContainsGivenResultsAfterTwoAppends) { - TestPartResultArray results; - results.Append(r1_); - results.Append(r2_); - EXPECT_EQ(2, results.size()); - EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message()); - EXPECT_STREQ("Failure 2", results.GetTestPartResult(1).message()); -} - -typedef TestPartResultArrayTest TestPartResultArrayDeathTest; - -// Tests that the program dies when GetTestPartResult() is called with -// an invalid index. -TEST_F(TestPartResultArrayDeathTest, DiesWhenIndexIsOutOfBound) { - TestPartResultArray results; - results.Append(r1_); - - EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(-1), ""); - EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(1), ""); -} - -// TODO(mheule@google.com): Add a test for the class HasNewFatalFailureHelper. - -} // namespace diff --git a/googletest/test/gtest_all_test.cc b/googletest/test/gtest_all_test.cc index e6c1b01..656066d 100644 --- a/googletest/test/gtest_all_test.cc +++ b/googletest/test/gtest_all_test.cc @@ -33,14 +33,14 @@ // // Sometimes it's desirable to build most of Google Test's own tests // by compiling a single file. This file serves this purpose. -#include "gtest-filepath_test.cc" -#include "gtest-linked_ptr_test.cc" -#include "gtest-message_test.cc" -#include "gtest-options_test.cc" -#include "gtest-port_test.cc" +#include "googletest-filepath-test.cc" +#include "googletest-linked-ptr-test.cc" +#include "googletest-message-test.cc" +#include "googletest-options-test.cc" +#include "googletest-port-test.cc" #include "gtest_pred_impl_unittest.cc" #include "gtest_prod_test.cc" -#include "gtest-test-part_test.cc" +#include "googletest-test-part-test.cc" #include "gtest-typed-test_test.cc" #include "gtest-typed-test2_test.cc" #include "gtest_unittest.cc" diff --git a/googletest/test/gtest_json_outfiles_test.py b/googletest/test/gtest_json_outfiles_test.py deleted file mode 100644 index 46010d8..0000000 --- a/googletest/test/gtest_json_outfiles_test.py +++ /dev/null @@ -1,162 +0,0 @@ -#!/usr/bin/env python -# Copyright 2018, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Unit test for the gtest_json_output module.""" - -import json -import os -import gtest_json_test_utils -import gtest_test_utils - -GTEST_OUTPUT_SUBDIR = 'json_outfiles' -GTEST_OUTPUT_1_TEST = 'gtest_xml_outfile1_test_' -GTEST_OUTPUT_2_TEST = 'gtest_xml_outfile2_test_' - -EXPECTED_1 = { - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'timestamp': u'*', - u'name': u'AllTests', - u'testsuites': [{ - u'name': u'PropertyOne', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [{ - u'name': u'TestSomeProperties', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyOne', - u'SetUpProp': u'1', - u'TestSomeProperty': u'1', - u'TearDownProp': u'1', - }], - }], -} - -EXPECTED_2 = { - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'timestamp': u'*', - u'name': u'AllTests', - u'testsuites': [{ - u'name': u'PropertyTwo', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [{ - u'name': u'TestSomeProperties', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyTwo', - u'SetUpProp': u'2', - u'TestSomeProperty': u'2', - u'TearDownProp': u'2', - }], - }], -} - - -class GTestJsonOutFilesTest(gtest_test_utils.TestCase): - """Unit test for Google Test's JSON output functionality.""" - - def setUp(self): - # We want the trailing '/' that the last "" provides in os.path.join, for - # telling Google Test to create an output directory instead of a single file - # for xml output. - self.output_dir_ = os.path.join(gtest_test_utils.GetTempDir(), - GTEST_OUTPUT_SUBDIR, '') - self.DeleteFilesAndDir() - - def tearDown(self): - self.DeleteFilesAndDir() - - def DeleteFilesAndDir(self): - try: - os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_1_TEST + '.json')) - except os.error: - pass - try: - os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_2_TEST + '.json')) - except os.error: - pass - try: - os.rmdir(self.output_dir_) - except os.error: - pass - - def testOutfile1(self): - self._TestOutFile(GTEST_OUTPUT_1_TEST, EXPECTED_1) - - def testOutfile2(self): - self._TestOutFile(GTEST_OUTPUT_2_TEST, EXPECTED_2) - - def _TestOutFile(self, test_name, expected): - gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name) - command = [gtest_prog_path, '--gtest_output=json:%s' % self.output_dir_] - p = gtest_test_utils.Subprocess(command, - working_dir=gtest_test_utils.GetTempDir()) - self.assert_(p.exited) - self.assertEquals(0, p.exit_code) - - # TODO(wan@google.com): libtool causes the built test binary to be - # named lt-gtest_xml_outfiles_test_ instead of - # gtest_xml_outfiles_test_. To account for this possibility, we - # allow both names in the following code. We should remove this - # hack when Chandler Carruth's libtool replacement tool is ready. - output_file_name1 = test_name + '.json' - output_file1 = os.path.join(self.output_dir_, output_file_name1) - output_file_name2 = 'lt-' + output_file_name1 - output_file2 = os.path.join(self.output_dir_, output_file_name2) - self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2), - output_file1) - - if os.path.isfile(output_file1): - with open(output_file1) as f: - actual = json.load(f) - else: - with open(output_file2) as f: - actual = json.load(f) - self.assertEqual(expected, gtest_json_test_utils.normalize(actual)) - - -if __name__ == '__main__': - os.environ['GTEST_STACK_TRACE_DEPTH'] = '0' - gtest_test_utils.Main() diff --git a/googletest/test/gtest_json_output_unittest.py b/googletest/test/gtest_json_output_unittest.py deleted file mode 100644 index 12047c4..0000000 --- a/googletest/test/gtest_json_output_unittest.py +++ /dev/null @@ -1,611 +0,0 @@ -#!/usr/bin/env python -# Copyright 2018, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Unit test for the gtest_json_output module.""" - -import datetime -import errno -import json -import os -import re -import sys - -import gtest_json_test_utils -import gtest_test_utils - -GTEST_FILTER_FLAG = '--gtest_filter' -GTEST_LIST_TESTS_FLAG = '--gtest_list_tests' -GTEST_OUTPUT_FLAG = '--gtest_output' -GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.json' -GTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_' - -SUPPORTS_STACK_TRACES = False - -if SUPPORTS_STACK_TRACES: - STACK_TRACE_TEMPLATE = '\nStack trace:\n*' -else: - STACK_TRACE_TEMPLATE = '' - -EXPECTED_NON_EMPTY = { - u'tests': 23, - u'failures': 4, - u'disabled': 2, - u'errors': 0, - u'timestamp': u'*', - u'time': u'*', - u'ad_hoc_property': u'42', - u'name': u'AllTests', - u'testsuites': [ - { - u'name': u'SuccessfulTest', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'Succeeds', - u'status': u'RUN', - u'time': u'*', - u'classname': u'SuccessfulTest' - } - ] - }, - { - u'name': u'FailedTest', - u'tests': 1, - u'failures': 1, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'Fails', - u'status': u'RUN', - u'time': u'*', - u'classname': u'FailedTest', - u'failures': [ - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Expected equality of these values:\n' - u' 1\n 2' + STACK_TRACE_TEMPLATE, - u'type': u'' - } - ] - } - ] - }, - { - u'name': u'DisabledTest', - u'tests': 1, - u'failures': 0, - u'disabled': 1, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'DISABLED_test_not_run', - u'status': u'NOTRUN', - u'time': u'*', - u'classname': u'DisabledTest' - } - ] - }, - { - u'name': u'MixedResultTest', - u'tests': 3, - u'failures': 1, - u'disabled': 1, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'Succeeds', - u'status': u'RUN', - u'time': u'*', - u'classname': u'MixedResultTest' - }, - { - u'name': u'Fails', - u'status': u'RUN', - u'time': u'*', - u'classname': u'MixedResultTest', - u'failures': [ - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Expected equality of these values:\n' - u' 1\n 2' + STACK_TRACE_TEMPLATE, - u'type': u'' - }, - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Expected equality of these values:\n' - u' 2\n 3' + STACK_TRACE_TEMPLATE, - u'type': u'' - } - ] - }, - { - u'name': u'DISABLED_test', - u'status': u'NOTRUN', - u'time': u'*', - u'classname': u'MixedResultTest' - } - ] - }, - { - u'name': u'XmlQuotingTest', - u'tests': 1, - u'failures': 1, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'OutputsCData', - u'status': u'RUN', - u'time': u'*', - u'classname': u'XmlQuotingTest', - u'failures': [ - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Failed\nXML output: ' - u'' + - STACK_TRACE_TEMPLATE, - u'type': u'' - } - ] - } - ] - }, - { - u'name': u'InvalidCharactersTest', - u'tests': 1, - u'failures': 1, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'InvalidCharactersInMessage', - u'status': u'RUN', - u'time': u'*', - u'classname': u'InvalidCharactersTest', - u'failures': [ - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Failed\nInvalid characters in brackets' - u' [\x01\x02]' + STACK_TRACE_TEMPLATE, - u'type': u'' - } - ] - } - ] - }, - { - u'name': u'PropertyRecordingTest', - u'tests': 4, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'SetUpTestCase': u'yes', - u'TearDownTestCase': u'aye', - u'testsuite': [ - { - u'name': u'OneProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyRecordingTest', - u'key_1': u'1' - }, - { - u'name': u'IntValuedProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyRecordingTest', - u'key_int': u'1' - }, - { - u'name': u'ThreeProperties', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyRecordingTest', - u'key_1': u'1', - u'key_2': u'2', - u'key_3': u'3' - }, - { - u'name': u'TwoValuesForOneKeyUsesLastValue', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyRecordingTest', - u'key_1': u'2' - } - ] - }, - { - u'name': u'NoFixtureTest', - u'tests': 3, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'RecordProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'NoFixtureTest', - u'key': u'1' - }, - { - u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'NoFixtureTest', - u'key_for_utility_int': u'1' - }, - { - u'name': - u'ExternalUtilityThatCallsRecordStringValuedProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'NoFixtureTest', - u'key_for_utility_string': u'1' - } - ] - }, - { - u'name': u'TypedTest/0', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'HasTypeParamAttribute', - u'type_param': u'int', - u'status': u'RUN', - u'time': u'*', - u'classname': u'TypedTest/0' - } - ] - }, - { - u'name': u'TypedTest/1', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'HasTypeParamAttribute', - u'type_param': u'long', - u'status': u'RUN', - u'time': u'*', - u'classname': u'TypedTest/1' - } - ] - }, - { - u'name': u'Single/TypeParameterizedTestCase/0', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'HasTypeParamAttribute', - u'type_param': u'int', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/TypeParameterizedTestCase/0' - } - ] - }, - { - u'name': u'Single/TypeParameterizedTestCase/1', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'HasTypeParamAttribute', - u'type_param': u'long', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/TypeParameterizedTestCase/1' - } - ] - }, - { - u'name': u'Single/ValueParamTest', - u'tests': 4, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'HasValueParamAttribute/0', - u'value_param': u'33', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/ValueParamTest' - }, - { - u'name': u'HasValueParamAttribute/1', - u'value_param': u'42', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/ValueParamTest' - }, - { - u'name': u'AnotherTestThatHasValueParamAttribute/0', - u'value_param': u'33', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/ValueParamTest' - }, - { - u'name': u'AnotherTestThatHasValueParamAttribute/1', - u'value_param': u'42', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/ValueParamTest' - } - ] - } - ] -} - -EXPECTED_FILTERED = { - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'timestamp': u'*', - u'name': u'AllTests', - u'ad_hoc_property': u'42', - u'testsuites': [{ - u'name': u'SuccessfulTest', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [{ - u'name': u'Succeeds', - u'status': u'RUN', - u'time': u'*', - u'classname': u'SuccessfulTest', - }] - }], -} - -EXPECTED_EMPTY = { - u'tests': 0, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'timestamp': u'*', - u'name': u'AllTests', - u'testsuites': [], -} - -GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME) - -SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess( - [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output - - -class GTestJsonOutputUnitTest(gtest_test_utils.TestCase): - """Unit test for Google Test's JSON output functionality. - """ - - # This test currently breaks on platforms that do not support typed and - # type-parameterized tests, so we don't run it under them. - if SUPPORTS_TYPED_TESTS: - - def testNonEmptyJsonOutput(self): - """Verifies JSON output for a Google Test binary with non-empty output. - - Runs a test program that generates a non-empty JSON output, and - tests that the JSON output is expected. - """ - self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY, 1) - - def testEmptyJsonOutput(self): - """Verifies JSON output for a Google Test binary without actual tests. - - Runs a test program that generates an empty JSON output, and - tests that the JSON output is expected. - """ - - self._TestJsonOutput('gtest_no_test_unittest', EXPECTED_EMPTY, 0) - - def testTimestampValue(self): - """Checks whether the timestamp attribute in the JSON output is valid. - - Runs a test program that generates an empty JSON output, and checks if - the timestamp attribute in the testsuites tag is valid. - """ - actual = self._GetJsonOutput('gtest_no_test_unittest', [], 0) - date_time_str = actual['timestamp'] - # datetime.strptime() is only available in Python 2.5+ so we have to - # parse the expected datetime manually. - match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str) - self.assertTrue( - re.match, - 'JSON datettime string %s has incorrect format' % date_time_str) - date_time_from_json = datetime.datetime( - year=int(match.group(1)), month=int(match.group(2)), - day=int(match.group(3)), hour=int(match.group(4)), - minute=int(match.group(5)), second=int(match.group(6))) - - time_delta = abs(datetime.datetime.now() - date_time_from_json) - # timestamp value should be near the current local time - self.assertTrue(time_delta < datetime.timedelta(seconds=600), - 'time_delta is %s' % time_delta) - - def testDefaultOutputFile(self): - """Verifies the default output file name. - - Confirms that Google Test produces an JSON output file with the expected - default name if no name is explicitly specified. - """ - output_file = os.path.join(gtest_test_utils.GetTempDir(), - GTEST_DEFAULT_OUTPUT_FILE) - gtest_prog_path = gtest_test_utils.GetTestExecutablePath( - 'gtest_no_test_unittest') - try: - os.remove(output_file) - except OSError: - e = sys.exc_info()[1] - if e.errno != errno.ENOENT: - raise - - p = gtest_test_utils.Subprocess( - [gtest_prog_path, '%s=json' % GTEST_OUTPUT_FLAG], - working_dir=gtest_test_utils.GetTempDir()) - self.assert_(p.exited) - self.assertEquals(0, p.exit_code) - self.assert_(os.path.isfile(output_file)) - - def testSuppressedJsonOutput(self): - """Verifies that no JSON output is generated. - - Tests that no JSON file is generated if the default JSON listener is - shut down before RUN_ALL_TESTS is invoked. - """ - - json_path = os.path.join(gtest_test_utils.GetTempDir(), - GTEST_PROGRAM_NAME + 'out.json') - if os.path.isfile(json_path): - os.remove(json_path) - - command = [GTEST_PROGRAM_PATH, - '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path), - '--shut_down_xml'] - p = gtest_test_utils.Subprocess(command) - if p.terminated_by_signal: - # p.signal is available only if p.terminated_by_signal is True. - self.assertFalse( - p.terminated_by_signal, - '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal)) - else: - self.assert_(p.exited) - self.assertEquals(1, p.exit_code, - "'%s' exited with code %s, which doesn't match " - 'the expected exit code %s.' - % (command, p.exit_code, 1)) - - self.assert_(not os.path.isfile(json_path)) - - def testFilteredTestJsonOutput(self): - """Verifies JSON output when a filter is applied. - - Runs a test program that executes only some tests and verifies that - non-selected tests do not show up in the JSON output. - """ - - self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED, 0, - extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG]) - - def _GetJsonOutput(self, gtest_prog_name, extra_args, expected_exit_code): - """Returns the JSON output generated by running the program gtest_prog_name. - - Furthermore, the program's exit code must be expected_exit_code. - - Args: - gtest_prog_name: Google Test binary name. - extra_args: extra arguments to binary invocation. - expected_exit_code: program's exit code. - """ - json_path = os.path.join(gtest_test_utils.GetTempDir(), - gtest_prog_name + 'out.json') - gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name) - - command = ( - [gtest_prog_path, '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path)] + - extra_args - ) - p = gtest_test_utils.Subprocess(command) - if p.terminated_by_signal: - self.assert_(False, - '%s was killed by signal %d' % (gtest_prog_name, p.signal)) - else: - self.assert_(p.exited) - self.assertEquals(expected_exit_code, p.exit_code, - "'%s' exited with code %s, which doesn't match " - 'the expected exit code %s.' - % (command, p.exit_code, expected_exit_code)) - with open(json_path) as f: - actual = json.load(f) - return actual - - def _TestJsonOutput(self, gtest_prog_name, expected, - expected_exit_code, extra_args=None): - """Checks the JSON output generated by the Google Test binary. - - Asserts that the JSON document generated by running the program - gtest_prog_name matches expected_json, a string containing another - JSON document. Furthermore, the program's exit code must be - expected_exit_code. - - Args: - gtest_prog_name: Google Test binary name. - expected: expected output. - expected_exit_code: program's exit code. - extra_args: extra arguments to binary invocation. - """ - - actual = self._GetJsonOutput(gtest_prog_name, extra_args or [], - expected_exit_code) - self.assertEqual(expected, gtest_json_test_utils.normalize(actual)) - - -if __name__ == '__main__': - os.environ['GTEST_STACK_TRACE_DEPTH'] = '1' - gtest_test_utils.Main() diff --git a/googletest/test/gtest_uninitialized_test_.cc b/googletest/test/gtest_uninitialized_test_.cc deleted file mode 100644 index 2ba0e8b..0000000 --- a/googletest/test/gtest_uninitialized_test_.cc +++ /dev/null @@ -1,43 +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. -// -// Author: wan@google.com (Zhanyong Wan) - -#include "gtest/gtest.h" - -TEST(DummyTest, Dummy) { - // This test doesn't verify anything. We just need it to create a - // realistic stage for testing the behavior of Google Test when - // RUN_ALL_TESTS() is called without - // testing::InitGoogleTest() being called first. -} - -int main() { - return RUN_ALL_TESTS(); -} -- cgit v0.12 From 5b9b39ff21db95ad68eeef105563aa71f3a23c32 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 17:25:56 -0400 Subject: Corresponding CMake Changes --- googletest/CMakeLists.txt | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index 2e412d7..518572f 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -86,7 +86,7 @@ include_directories( if (MSVC AND MSVC_VERSION EQUAL 1700) add_definitions(/D _VARIADIC_MAX=10) endif() - + ######################################################################## # # Defines the gtest & gtest_main libraries. User tests should link @@ -171,28 +171,28 @@ if (gtest_build_tests) ############################################################ # C++ tests built with standard compiler flags. - cxx_test(gtest-death-test_test gtest_main) + cxx_test(googletest-death-test-test gtest_main) cxx_test(gtest_environment_test gtest) - cxx_test(gtest-filepath_test gtest_main) - cxx_test(gtest-linked_ptr_test gtest_main) - cxx_test(gtest-listener_test gtest_main) + cxx_test(googletest-filepath-test gtest_main) + cxx_test(googletest-linked-ptr-test gtest_main) + cxx_test(googletest-listener-test gtest_main) cxx_test(gtest_main_unittest gtest_main) - cxx_test(gtest-message_test gtest_main) + cxx_test(googletest-message-test gtest_main) cxx_test(gtest_no_test_unittest gtest) - cxx_test(gtest-options_test gtest_main) - cxx_test(gtest-param-test_test gtest - test/gtest-param-test2_test.cc) - cxx_test(gtest-port_test gtest_main) + cxx_test(googletest-options-test gtest_main) + cxx_test(googletest-param-test-test gtest + test/googletest-param-test2-test.cc) + cxx_test(googletest-port-test gtest_main) cxx_test(gtest_pred_impl_unittest gtest_main) cxx_test(gtest_premature_exit_test gtest test/gtest_premature_exit_test.cc) - cxx_test(gtest-printers_test gtest_main) + cxx_test(googletest-printers-test gtest_main) cxx_test(gtest_prod_test gtest_main test/production.cc) cxx_test(gtest_repeat_test gtest) cxx_test(gtest_sole_header_test gtest_main) cxx_test(gtest_stress_test gtest) - cxx_test(gtest-test-part_test gtest_main) + cxx_test(googletest-test-part-test gtest_main) cxx_test(gtest_throw_on_failure_ex_test gtest) cxx_test(gtest-typed-test_test gtest_main test/gtest-typed-test2_test.cc) -- cgit v0.12 From f3511bf1c703c31c226cab29bd04106cdeb5f2ac Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 2 Aug 2018 14:56:33 -0400 Subject: cleaning up and adding test changes to CMake --- googletest/CMakeLists.txt | 8 ++++---- googletest/Makefile.am | 24 ++++++++++++------------ googletest/test/BUILD.bazel | 2 +- googletest/test/googletest-param-test2-test.cc | 6 +++--- googletest/test/googletest-test2_test.cc | 6 +++--- googletest/test/gtest_unittest.cc | 2 +- 6 files changed, 24 insertions(+), 24 deletions(-) diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index 518572f..0e0e4ca 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -239,11 +239,11 @@ if (gtest_build_tests) src/gtest-all.cc src/gtest_main.cc) cxx_test_with_flags(gtest-tuple_test "${cxx_use_own_tuple}" - gtest_main_use_own_tuple test/gtest-tuple_test.cc) + gtest_main_use_own_tuple test/googletest-tuple-test.cc) cxx_test_with_flags(gtest_use_own_tuple_test "${cxx_use_own_tuple}" gtest_main_use_own_tuple - test/gtest-param-test_test.cc test/gtest-param-test2_test.cc) + test/googletest-param-test-test.cc test/gtest-param-test2_test.cc) endif() ############################################################ @@ -258,14 +258,14 @@ if (gtest_build_tests) gtest_catch_exceptions_no_ex_test_ "${cxx_no_exception}" gtest_main_no_exception - test/gtest_catch_exceptions_test_.cc) + test/googletest-catch-exceptions-test_.cc) endif() cxx_executable_with_flags( gtest_catch_exceptions_ex_test_ "${cxx_exception}" gtest_main - test/gtest_catch_exceptions_test_.cc) + test/googletest-catch-exceptions-test_.cc) py_test(gtest_catch_exceptions_test) cxx_executable(gtest_color_test_ test gtest) diff --git a/googletest/Makefile.am b/googletest/Makefile.am index b6c7232..b32131d 100644 --- a/googletest/Makefile.am +++ b/googletest/Makefile.am @@ -55,38 +55,38 @@ EXTRA_DIST += \ test/gtest-options_test.cc \ test/gtest-param-test2_test.cc \ test/gtest-param-test2_test.cc \ - test/gtest-param-test_test.cc \ - test/gtest-param-test_test.cc \ + test/googletest-param-test-test.cc \ + test/googletest-param-test-test.cc \ test/gtest-param-test_test.h \ test/gtest-port_test.cc \ test/gtest_premature_exit_test.cc \ test/gtest-printers_test.cc \ test/gtest-test-part_test.cc \ - test/gtest-tuple_test.cc \ + test/googletest-tuple-test.cc \ test/gtest-typed-test2_test.cc \ test/gtest-typed-test_test.cc \ test/gtest-typed-test_test.h \ test/gtest-unittest-api_test.cc \ - test/gtest_break_on_failure_unittest_.cc \ - test/gtest_catch_exceptions_test_.cc \ - test/gtest_color_test_.cc \ + test/googletest-break-on-failure-unittest_.cc \ + test/googletest-catch-exceptions-test_.cc \ + test/googletest-color-test_.cc \ test/gtest_env_var_test_.cc \ test/gtest_environment_test.cc \ - test/gtest_filter_unittest_.cc \ + test/googletest-filter-unittest_.cc \ test/gtest_help_test_.cc \ - test/gtest_list_tests_unittest_.cc \ + test/googletest-list-tests-unittest_.cc \ test/gtest_main_unittest.cc \ test/gtest_no_test_unittest.cc \ - test/gtest_output_test_.cc \ + test/googletest-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/googletest-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/googletest-throw-on-failure-test_.cc \ + test/googletest-uninitialized-test_.cc \ test/gtest_unittest.cc \ test/gtest_unittest.cc \ test/gtest_xml_outfile1_test_.cc \ diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 3f6d466..2a12f5a 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -68,7 +68,7 @@ cc_test( "gtest-death-test_ex_test.cc", "gtest-listener_test.cc", "gtest-unittest-api_test.cc", - "gtest-param-test_test.cc", + "googletest-param-test-test.cc", "googletest-catch-exceptions-test_.cc", "googletest-color-test_.cc", "googletest-env-var-test_.cc", diff --git a/googletest/test/googletest-param-test2-test.cc b/googletest/test/googletest-param-test2-test.cc index c0db7bf..c0a908b 100644 --- a/googletest/test/googletest-param-test2-test.cc +++ b/googletest/test/googletest-param-test2-test.cc @@ -40,11 +40,11 @@ using ::testing::internal::ParamGenerator; // Tests that generators defined in a different translation unit // are functional. The test using extern_gen is defined -// in gtest-param-test_test.cc. +// in googletest-param-test-test.cc. ParamGenerator extern_gen = Values(33); // Tests that a parameterized test case can be defined in one translation unit -// and instantiated in another. The test is defined in gtest-param-test_test.cc +// and instantiated in another. The test is defined in googletest-param-test-test.cc // and ExternalInstantiationTest fixture class is defined in // gtest-param-test_test.h. INSTANTIATE_TEST_CASE_P(MultiplesOf33, @@ -53,7 +53,7 @@ INSTANTIATE_TEST_CASE_P(MultiplesOf33, // Tests that a parameterized test case can be instantiated // in multiple translation units. Another instantiation is defined -// in gtest-param-test_test.cc and InstantiationInMultipleTranslaionUnitsTest +// in googletest-param-test-test.cc and InstantiationInMultipleTranslaionUnitsTest // fixture is defined in gtest-param-test_test.h INSTANTIATE_TEST_CASE_P(Sequence2, InstantiationInMultipleTranslaionUnitsTest, diff --git a/googletest/test/googletest-test2_test.cc b/googletest/test/googletest-test2_test.cc index 732e356..e50c259 100644 --- a/googletest/test/googletest-test2_test.cc +++ b/googletest/test/googletest-test2_test.cc @@ -40,11 +40,11 @@ using ::testing::internal::ParamGenerator; // Tests that generators defined in a different translation unit // are functional. The test using extern_gen_2 is defined -// in gtest-param-test_test.cc. +// in googletest-param-test-test.cc. ParamGenerator extern_gen_2 = Values(33); // Tests that a parameterized test case can be defined in one translation unit -// and instantiated in another. The test is defined in gtest-param-test_test.cc +// and instantiated in another. The test is defined in googletest-param-test-test.cc // and ExternalInstantiationTest fixture class is defined in // gtest-param-test_test.h. INSTANTIATE_TEST_CASE_P(MultiplesOf33, @@ -53,7 +53,7 @@ INSTANTIATE_TEST_CASE_P(MultiplesOf33, // Tests that a parameterized test case can be instantiated // in multiple translation units. Another instantiation is defined -// in gtest-param-test_test.cc and InstantiationInMultipleTranslaionUnitsTest +// in googletest-param-test-test.cc and InstantiationInMultipleTranslaionUnitsTest // fixture is defined in gtest-param-test_test.h INSTANTIATE_TEST_CASE_P(Sequence2, InstantiationInMultipleTranslaionUnitsTest, diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 8ebb667..46eb7b2 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -4689,7 +4689,7 @@ TEST(MacroTest, ADD_FAILURE_AT) { // 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. + // line number. Instead, we do that in googletest-output-test_.cc. } // Tests FAIL. -- cgit v0.12 From 930f0f86e303227a9e794489db4e303bf2c22745 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 2 Aug 2018 15:45:23 -0400 Subject: cmake tests changes --- googletest/CMakeLists.txt | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index 0e0e4ca..cd8c450 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -214,10 +214,10 @@ if (gtest_build_tests) cxx_test_with_flags(gtest-death-test_ex_nocatch_test "${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=0" - gtest test/gtest-death-test_ex_test.cc) + gtest test/googletest-death-test_ex_test.cc) cxx_test_with_flags(gtest-death-test_ex_catch_test "${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=1" - gtest test/gtest-death-test_ex_test.cc) + gtest test/googletest-death-test_ex_test.cc) cxx_test_with_flags(gtest_no_rtti_unittest "${cxx_no_rtti}" gtest_main_no_rtti test/gtest_unittest.cc) @@ -238,7 +238,7 @@ if (gtest_build_tests) cxx_library(gtest_main_use_own_tuple "${cxx_use_own_tuple}" src/gtest-all.cc src/gtest_main.cc) - cxx_test_with_flags(gtest-tuple_test "${cxx_use_own_tuple}" + cxx_test_with_flags(googletest-tuple-test "${cxx_use_own_tuple}" gtest_main_use_own_tuple test/googletest-tuple-test.cc) cxx_test_with_flags(gtest_use_own_tuple_test "${cxx_use_own_tuple}" @@ -249,7 +249,7 @@ if (gtest_build_tests) ############################################################ # Python tests. - cxx_executable(gtest_break_on_failure_unittest_ test gtest) + cxx_executable(googletest-break-on-failure-unittest_ test gtest) py_test(gtest_break_on_failure_unittest) # Visual Studio .NET 2003 does not support STL with exceptions disabled. @@ -268,37 +268,37 @@ if (gtest_build_tests) test/googletest-catch-exceptions-test_.cc) py_test(gtest_catch_exceptions_test) - cxx_executable(gtest_color_test_ test gtest) + cxx_executable(googletest-color-test_ test gtest) py_test(gtest_color_test) cxx_executable(gtest_env_var_test_ test gtest) py_test(gtest_env_var_test) - cxx_executable(gtest_filter_unittest_ test gtest) + cxx_executable(googletest-filter-unittest_ test gtest) py_test(gtest_filter_unittest) cxx_executable(gtest_help_test_ test gtest_main) py_test(gtest_help_test) - cxx_executable(gtest_list_tests_unittest_ test gtest) + cxx_executable(googletest-list-tests-unittest_ test gtest) py_test(gtest_list_tests_unittest) - cxx_executable(gtest_output_test_ test gtest) + cxx_executable(googletest-output-test_ test gtest) py_test(gtest_output_test --no_stacktrace_support) - cxx_executable(gtest_shuffle_test_ test gtest) + cxx_executable(googletest-shuffle-test_ test gtest) py_test(gtest_shuffle_test) # MSVC 7.1 does not support STL with exceptions disabled. if (NOT MSVC OR MSVC_VERSION GREATER 1310) - cxx_executable(gtest_throw_on_failure_test_ test gtest_no_exception) - set_target_properties(gtest_throw_on_failure_test_ + cxx_executable(googletest-throw-on-failure-test_ test gtest_no_exception) + set_target_properties(googletest-throw-on-failure-test_ PROPERTIES COMPILE_FLAGS "${cxx_no_exception}") py_test(gtest_throw_on_failure_test) endif() - cxx_executable(gtest_uninitialized_test_ test gtest) + cxx_executable(googletest-uninitialized-test_ test gtest) py_test(gtest_uninitialized_test) cxx_executable(gtest_xml_outfile1_test_ test gtest_main) -- cgit v0.12 From b7244ff37c1973f7bc9b41f9dc311de0813f580e Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 2 Aug 2018 16:01:00 -0400 Subject: cmake fixes --- googletest/CMakeLists.txt | 4 ++-- googletest/Makefile.am | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index cd8c450..4225b24 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -243,7 +243,7 @@ if (gtest_build_tests) cxx_test_with_flags(gtest_use_own_tuple_test "${cxx_use_own_tuple}" gtest_main_use_own_tuple - test/googletest-param-test-test.cc test/gtest-param-test2_test.cc) + test/googletest-param-test-test.cc test/googletest-param-test2-test.cc) endif() ############################################################ @@ -271,7 +271,7 @@ if (gtest_build_tests) cxx_executable(googletest-color-test_ test gtest) py_test(gtest_color_test) - cxx_executable(gtest_env_var_test_ test gtest) + cxx_executable(googletest-env-var-test_ test gtest) py_test(gtest_env_var_test) cxx_executable(googletest-filter-unittest_ test gtest) diff --git a/googletest/Makefile.am b/googletest/Makefile.am index b32131d..69c2312 100644 --- a/googletest/Makefile.am +++ b/googletest/Makefile.am @@ -53,8 +53,8 @@ EXTRA_DIST += \ test/gtest-listener_test.cc \ test/gtest-message_test.cc \ test/gtest-options_test.cc \ - test/gtest-param-test2_test.cc \ - test/gtest-param-test2_test.cc \ + test/googletest-param-test2-test.cc \ + test/googletest-param-test2-test.cc \ test/googletest-param-test-test.cc \ test/googletest-param-test-test.cc \ test/gtest-param-test_test.h \ @@ -70,7 +70,7 @@ EXTRA_DIST += \ test/googletest-break-on-failure-unittest_.cc \ test/googletest-catch-exceptions-test_.cc \ test/googletest-color-test_.cc \ - test/gtest_env_var_test_.cc \ + test/googletest-env-var-test_.cc \ test/gtest_environment_test.cc \ test/googletest-filter-unittest_.cc \ test/gtest_help_test_.cc \ -- cgit v0.12 From 677df883ece2d560cb4724041b8624065ffbf069 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 2 Aug 2018 16:24:09 -0400 Subject: cmake test fixes --- googletest/CMakeLists.txt | 24 +++++++++++----------- googletest/Makefile.am | 22 ++++++++++---------- .../test/googletest-catch-exceptions-test.py | 4 ++-- .../test/googletest-catch-exceptions-test_.cc | 2 +- googletest/test/googletest-output-test_.cc | 2 +- .../test/googletest-throw-on-failure-test.py | 2 +- 6 files changed, 28 insertions(+), 28 deletions(-) diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index 4225b24..af88e6d 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -250,7 +250,7 @@ if (gtest_build_tests) # Python tests. cxx_executable(googletest-break-on-failure-unittest_ test gtest) - py_test(gtest_break_on_failure_unittest) + py_test(googletest-break-on-failure-unittest) # Visual Studio .NET 2003 does not support STL with exceptions disabled. if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003 @@ -266,28 +266,28 @@ if (gtest_build_tests) "${cxx_exception}" gtest_main test/googletest-catch-exceptions-test_.cc) - py_test(gtest_catch_exceptions_test) + py_test(googletest-catch-exceptions-test) cxx_executable(googletest-color-test_ test gtest) - py_test(gtest_color_test) + py_test(googletest-color-test) cxx_executable(googletest-env-var-test_ test gtest) - py_test(gtest_env_var_test) + py_test(googletest-env-var-test) cxx_executable(googletest-filter-unittest_ test gtest) - py_test(gtest_filter_unittest) + py_test(googletest-filter-unittest) cxx_executable(gtest_help_test_ test gtest_main) py_test(gtest_help_test) cxx_executable(googletest-list-tests-unittest_ test gtest) - py_test(gtest_list_tests_unittest) + py_test(googletest-list-tests-unittest) cxx_executable(googletest-output-test_ test gtest) - py_test(gtest_output_test --no_stacktrace_support) + py_test(googletest-output-test --no_stacktrace_support) cxx_executable(googletest-shuffle-test_ test gtest) - py_test(gtest_shuffle_test) + py_test(googletest-shuffle-test) # MSVC 7.1 does not support STL with exceptions disabled. if (NOT MSVC OR MSVC_VERSION GREATER 1310) @@ -295,18 +295,18 @@ if (gtest_build_tests) set_target_properties(googletest-throw-on-failure-test_ PROPERTIES COMPILE_FLAGS "${cxx_no_exception}") - py_test(gtest_throw_on_failure_test) + py_test(googletest-throw-on-failure-test) endif() cxx_executable(googletest-uninitialized-test_ test gtest) - py_test(gtest_uninitialized_test) + py_test(googletest-uninitialized-test) cxx_executable(gtest_xml_outfile1_test_ test gtest_main) cxx_executable(gtest_xml_outfile2_test_ test gtest_main) py_test(gtest_xml_outfiles_test) - py_test(gtest_json_outfiles_test) + py_test(googletest-json-outfiles-test) cxx_executable(gtest_xml_output_unittest_ test gtest) py_test(gtest_xml_output_unittest --no_stacktrace_support) - py_test(gtest_json_output_unittest) + py_test(googletest-json-output-unittest) endif() diff --git a/googletest/Makefile.am b/googletest/Makefile.am index 69c2312..b44c841 100644 --- a/googletest/Makefile.am +++ b/googletest/Makefile.am @@ -97,19 +97,19 @@ EXTRA_DIST += \ # Python tests that we don't run. EXTRA_DIST += \ - test/gtest_break_on_failure_unittest.py \ - test/gtest_catch_exceptions_test.py \ - test/gtest_color_test.py \ - test/gtest_env_var_test.py \ - test/gtest_filter_unittest.py \ + test/googletest-break-on-failure-unittest.py \ + test/googletest-catch-exceptions-test.py \ + test/googletest-color-test.py \ + test/googletest-env-var-test.py \ + test/googletest-filter-unittest.py \ test/gtest_help_test.py \ - test/gtest_list_tests_unittest.py \ - test/gtest_output_test.py \ - test/gtest_output_test_golden_lin.txt \ - test/gtest_shuffle_test.py \ + test/googletest-list-tests-unittest.py \ + test/googletest-output-test.py \ + test/googletest-output-test_golden_lin.txt \ + test/googletest-shuffle-test.py \ test/gtest_test_utils.py \ - test/gtest_throw_on_failure_test.py \ - test/gtest_uninitialized_test.py \ + test/googletest-throw-on-failure-test.py \ + test/googletest-uninitialized-test.py \ test/gtest_xml_outfiles_test.py \ test/gtest_xml_output_unittest.py \ test/gtest_xml_test_utils.py diff --git a/googletest/test/googletest-catch-exceptions-test.py b/googletest/test/googletest-catch-exceptions-test.py index d12a32a..cda61b2 100755 --- a/googletest/test/googletest-catch-exceptions-test.py +++ b/googletest/test/googletest-catch-exceptions-test.py @@ -30,7 +30,7 @@ """Tests Google Test's exception catching behavior. -This script invokes gtest_catch_exceptions_test_ and +This script invokes googletest-catch-exceptions-test_ and gtest_catch_exceptions_ex_test_ (programs written with Google Test) and verifies their output. """ @@ -50,7 +50,7 @@ FILTER_FLAG = FLAG_PREFIX + 'filter' EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath( 'googletest_catch_exceptions_ex_test_') -# Path to the gtest_catch_exceptions_test_ binary, compiled with +# Path to the googletest-catch-exceptions-test_ binary, compiled with # exceptions disabled. EXE_PATH = gtest_test_utils.GetTestExecutablePath( 'googletest_catch_exceptions_no_ex_test_') diff --git a/googletest/test/googletest-catch-exceptions-test_.cc b/googletest/test/googletest-catch-exceptions-test_.cc index c6d953c..cb018f9 100644 --- a/googletest/test/googletest-catch-exceptions-test_.cc +++ b/googletest/test/googletest-catch-exceptions-test_.cc @@ -30,7 +30,7 @@ // 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. +// exceptions, and the output is verified by googletest-catch-exceptions-test.py. #include "gtest/gtest.h" diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index 9ae9dc6..29fc993 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -29,7 +29,7 @@ // // The purpose of this file is to generate Google Test output under // various conditions. The output will then be verified by -// gtest_output_test.py to ensure that Google Test generates the +// googletest-output-test.py to ensure that Google Test generates the // desired messages. Therefore, most tests in this file are MEANT TO // FAIL. // diff --git a/googletest/test/googletest-throw-on-failure-test.py b/googletest/test/googletest-throw-on-failure-test.py index 7253cfd..26ba32b 100755 --- a/googletest/test/googletest-throw-on-failure-test.py +++ b/googletest/test/googletest-throw-on-failure-test.py @@ -76,7 +76,7 @@ def Run(command): # The tests. TODO(wan@google.com): refactor the class to share common -# logic with code in gtest_break_on_failure_unittest.py. +# logic with code in googletest-break-on-failure-unittest.py. class ThrowOnFailureTest(gtest_test_utils.TestCase): """Tests the throw-on-failure mode.""" -- cgit v0.12 From 94f2c6faa74a0785b851fa8e66cb851f49aa92ce Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 2 Aug 2018 16:51:03 -0400 Subject: fixes tests --- googletest/test/BUILD.bazel | 4 ++-- googletest/test/googletest-catch-exceptions-test.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 2a12f5a..5227680 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -341,7 +341,7 @@ cc_binary( ) cc_binary( - name = "googletest_catch_exceptions_ex_test_", + name = "googletest-catch-exceptions-ex-test_", testonly = 1, srcs = ["googletest-catch-exceptions-test_.cc"], copts = ["-fexceptions"], @@ -353,7 +353,7 @@ py_test( size = "small", srcs = ["googletest-catch-exceptions-test.py"], data = [ - ":googletest_catch_exceptions_ex_test_", + ":googletest-catch-exceptions-ex-test_", ":googletest_catch_exceptions_no_ex_test_", ], deps = [":gtest_test_utils"], diff --git a/googletest/test/googletest-catch-exceptions-test.py b/googletest/test/googletest-catch-exceptions-test.py index cda61b2..0bd4366 100755 --- a/googletest/test/googletest-catch-exceptions-test.py +++ b/googletest/test/googletest-catch-exceptions-test.py @@ -48,7 +48,7 @@ FILTER_FLAG = FLAG_PREFIX + 'filter' # Path to the gtest_catch_exceptions_ex_test_ binary, compiled with # exceptions enabled. EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath( - 'googletest_catch_exceptions_ex_test_') + 'googletest-catch-exceptions-ex-test_') # Path to the googletest-catch-exceptions-test_ binary, compiled with # exceptions disabled. -- cgit v0.12 From 95c313e68541a1a63adbb6639a5e5745360bfd06 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 2 Aug 2018 16:58:11 -0400 Subject: add --no_stacktrace_support for json-output-unittest --- googletest/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index af88e6d..615b071 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -308,5 +308,5 @@ if (gtest_build_tests) cxx_executable(gtest_xml_output_unittest_ test gtest) py_test(gtest_xml_output_unittest --no_stacktrace_support) - py_test(googletest-json-output-unittest) + py_test(googletest-json-output-unittest --no_stacktrace_support) endif() -- cgit v0.12 From 0d29f9702df3a9b8fd4771e5725dc301f9797539 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 2 Aug 2018 17:32:43 -0400 Subject: more fixes --- googletest/CMakeLists.txt | 2 +- googletest/test/googletest-catch-exceptions-test.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index 615b071..4f340bb 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -262,7 +262,7 @@ if (gtest_build_tests) endif() cxx_executable_with_flags( - gtest_catch_exceptions_ex_test_ + googletest-catch-exceptions-ex-test_ "${cxx_exception}" gtest_main test/googletest-catch-exceptions-test_.cc) diff --git a/googletest/test/googletest-catch-exceptions-test.py b/googletest/test/googletest-catch-exceptions-test.py index 0bd4366..5f13efa 100755 --- a/googletest/test/googletest-catch-exceptions-test.py +++ b/googletest/test/googletest-catch-exceptions-test.py @@ -31,7 +31,7 @@ """Tests Google Test's exception catching behavior. This script invokes googletest-catch-exceptions-test_ and -gtest_catch_exceptions_ex_test_ (programs written with +googletest-catch-exceptions-ex-test_ (programs written with Google Test) and verifies their output. """ @@ -45,7 +45,7 @@ LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests' NO_CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions=0' FILTER_FLAG = FLAG_PREFIX + 'filter' -# Path to the gtest_catch_exceptions_ex_test_ binary, compiled with +# Path to the googletest-catch-exceptions-ex-test_ binary, compiled with # exceptions enabled. EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath( 'googletest-catch-exceptions-ex-test_') -- cgit v0.12 From b929d55704e4312f80e6aebad0750966f65d9fb4 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 2 Aug 2018 17:46:43 -0400 Subject: cmake fixes --- googletest/test/BUILD.bazel | 4 ++-- googletest/test/googletest-catch-exceptions-test.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 5227680..a930d65 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -334,7 +334,7 @@ py_test( ) cc_binary( - name = "googletest_catch_exceptions_no_ex_test_", + name = "googletest-catch-exceptions-no-ex-test_", testonly = 1, srcs = ["googletest-catch-exceptions-test_.cc"], deps = ["//:gtest_main"], @@ -354,7 +354,7 @@ py_test( srcs = ["googletest-catch-exceptions-test.py"], data = [ ":googletest-catch-exceptions-ex-test_", - ":googletest_catch_exceptions_no_ex_test_", + ":googletest-catch-exceptions-no-ex-test_", ], deps = [":gtest_test_utils"], ) diff --git a/googletest/test/googletest-catch-exceptions-test.py b/googletest/test/googletest-catch-exceptions-test.py index 5f13efa..69dbadf 100755 --- a/googletest/test/googletest-catch-exceptions-test.py +++ b/googletest/test/googletest-catch-exceptions-test.py @@ -53,7 +53,7 @@ EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath( # Path to the googletest-catch-exceptions-test_ binary, compiled with # exceptions disabled. EXE_PATH = gtest_test_utils.GetTestExecutablePath( - 'googletest_catch_exceptions_no_ex_test_') + 'googletest-catch-exceptions-no-ex-test_') environ = gtest_test_utils.environ SetEnvVar = gtest_test_utils.SetEnvVar -- cgit v0.12 From 2a7077fa2428e5df867a1028b1175c557e7b8fb2 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 2 Aug 2018 20:03:26 -0700 Subject: one more fix --- googletest/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index 4f340bb..ba2c2c2 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -255,7 +255,7 @@ if (gtest_build_tests) # Visual Studio .NET 2003 does not support STL with exceptions disabled. if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003 cxx_executable_with_flags( - gtest_catch_exceptions_no_ex_test_ + googletest-catch-exceptions-no-ex-test_ "${cxx_no_exception}" gtest_main_no_exception test/googletest-catch-exceptions-test_.cc) -- cgit v0.12 From 51b65058ad72d2d92fff89f04aad99f8bbddb147 Mon Sep 17 00:00:00 2001 From: wxf Date: Fri, 3 Aug 2018 16:23:38 +0800 Subject: Ignore cmake generated files when used as submodule --- .gitignore | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.gitignore b/.gitignore index 16c56e6..73cdd2c 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,14 @@ googletest/fused-src/ # macOS files .DS_Store + +# Ignore cmake generated directories and files. +CMakeFiles +CTestTestfile.cmake +Makefile +cmake_install.cmake +googlemock/CMakeFiles +googlemock/CTestTestfile.cmake +googlemock/Makefile +googlemock/cmake_install.cmake +googlemock/gtest -- cgit v0.12 From 1da26a77c55387b88061cc7196d77e9f8e5362ae Mon Sep 17 00:00:00 2001 From: Philipp Paulweber Date: Thu, 19 Jul 2018 12:36:47 +0200 Subject: Printers test: fixed compilation bug, due to unnecessary parentheses in declaration --- googletest/test/googletest-printers-test.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index 49b3bd4..1b1026e 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -572,7 +572,7 @@ struct Foo { TEST(PrintPointerTest, MemberVariablePointer) { EXPECT_TRUE(HasPrefix(Print(&Foo::value), Print(sizeof(&Foo::value)) + "-byte object ")); - int (Foo::*p) = NULL; // NOLINT + int Foo::*p = NULL; // NOLINT EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object ")); } @@ -1250,7 +1250,7 @@ TEST(PrintReferenceTest, HandlesMemberFunctionPointer) { // Tests that the universal printer prints a member variable pointer // passed by reference. TEST(PrintReferenceTest, HandlesMemberVariablePointer) { - int (Foo::*p) = &Foo::value; // NOLINT + int Foo::*p = &Foo::value; // NOLINT EXPECT_TRUE(HasPrefix( PrintByRef(p), "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object ")); -- cgit v0.12 From 5d2e503574703da547390fe715df771cd4bf763a Mon Sep 17 00:00:00 2001 From: Wez Date: Fri, 3 Aug 2018 16:26:16 -0700 Subject: No default exception handling --- googletest/src/gtest-death-test.cc | 65 +++++++++++++++++++++++++++++--------- 1 file changed, 50 insertions(+), 15 deletions(-) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 2f772f6..8ae9968 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -67,6 +67,7 @@ # include # include # include +# include # endif // GTEST_OS_FUCHSIA #endif // GTEST_HAS_DEATH_TEST @@ -805,6 +806,12 @@ class FuchsiaDeathTest : public DeathTestImpl { const char* file, int line) : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {} + virtual ~FuchsiaDeathTest() { + zx_status_t status = zx_handle_close(child_process_); + GTEST_DEATH_TEST_CHECK_(status == ZX_OK); + status = zx_handle_close(port_); + GTEST_DEATH_TEST_CHECK_(status == ZX_OK); + } // All of these virtual functions are inherited from DeathTest. virtual int Wait(); @@ -816,7 +823,8 @@ class FuchsiaDeathTest : public DeathTestImpl { // The line number on which the death test is located. const int line_; - zx_handle_t child_process_; + zx_handle_t child_process_ = ZX_HANDLE_INVALID; + zx_handle_t port_ = ZX_HANDLE_INVALID; }; // Utility class for accumulating command-line arguments. @@ -863,16 +871,38 @@ int FuchsiaDeathTest::Wait() { if (!spawned()) return 0; - // Wait for child process to terminate. + // Register to wait for the child process to terminate. zx_status_t status_zx; - zx_signals_t signals; - status_zx = zx_object_wait_one( - child_process_, - ZX_PROCESS_TERMINATED, - ZX_TIME_INFINITE, - &signals); + status_zx = zx_object_wait_async(child_process_, + port_, + 0 /* key */, + ZX_PROCESS_TERMINATED, + ZX_WAIT_ASYNC_ONCE); + GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); + + // Wait for it to terminate, or an exception to be received. + zx_port_packet_t packet; + status_zx = zx_port_wait(port_, ZX_TIME_INFINITE, &packet); GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); + if (ZX_PKT_IS_EXCEPTION(packet.type)) { + // Process encountered an exception. Kill it directly rather than letting + // other handlers process the event. + status_zx = zx_task_kill(child_process_); + GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); + + // Now wait for |child_process_| to terminate. + zx_signals_t signals = 0; + status_zx = zx_object_wait_one( + child_process_, ZX_PROCESS_TERMINATED, ZX_TIME_INFINITE, &signals); + GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); + GTEST_DEATH_TEST_CHECK_(signals & ZX_PROCESS_TERMINATED); + } else { + // Process terminated. + GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type)); + GTEST_DEATH_TEST_CHECK_(packet.observed & ZX_PROCESS_TERMINATED); + } + ReadAndInterpretStatusByte(); zx_info_process_t buffer; @@ -936,13 +966,10 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { set_read_fd(status); // Set the pipe handle for the child. - fdio_spawn_action_t add_handle_action = { - .action = FDIO_SPAWN_ACTION_ADD_HANDLE, - .h = { - .id = PA_HND(type, kFuchsiaReadPipeFd), - .handle = child_pipe_handle - } - }; + fdio_spawn_action_t add_handle_action = {}; + add_handle_action.action = FDIO_SPAWN_ACTION_ADD_HANDLE; + add_handle_action.h.id = PA_HND(type, kFuchsiaReadPipeFd); + add_handle_action.h.handle = child_pipe_handle; // Spawn the child process. status = fdio_spawn_etc(ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL, @@ -950,6 +977,14 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { &add_handle_action, &child_process_, nullptr); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); + // Create an exception port and attach it to the |child_process_|, to allow + // us to suppress the system default exception handler from firing. + status = zx_port_create(0, &port_); + GTEST_DEATH_TEST_CHECK_(status == ZX_OK); + status = zx_task_bind_exception_port( + child_process_, port_, 0 /* key */, 0 /*options */); + GTEST_DEATH_TEST_CHECK_(status == ZX_OK); + set_spawned(true); return OVERSEE_TEST; } -- cgit v0.12 From 24edf4e3bfc132fe21509ed5fba394ddcc02cb5f Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 6 Aug 2018 15:40:21 -0400 Subject: automatic code sync mgt, comment only --- googlemock/test/gmock-actions_test.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index e8bdbee..2d169f8 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -937,6 +937,8 @@ class Foo { int value_; }; +// GOOGLETEST_CM0005 DO NOT DELETE + // Tests InvokeWithoutArgs(function). TEST(InvokeWithoutArgsTest, Function) { // As an action that takes one argument. -- cgit v0.12 From b78c3b8e008ea8ef059d224ece6aa52a4727ae2c Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Tue, 7 Aug 2018 10:38:41 -0400 Subject: small cleanup, np functional changes --- googlemock/test/gmock-actions_test.cc | 2 -- 1 file changed, 2 deletions(-) diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index 2d169f8..e8bdbee 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -937,8 +937,6 @@ class Foo { int value_; }; -// GOOGLETEST_CM0005 DO NOT DELETE - // Tests InvokeWithoutArgs(function). TEST(InvokeWithoutArgsTest, Function) { // As an action that takes one argument. -- cgit v0.12 From b345bf9090961139971775105fa120cc87d63e44 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Tue, 7 Aug 2018 11:49:47 -0400 Subject: Formatting changes,small cleanup, no functionality changes --- googlemock/src/gmock_main.cc | 3 ++- googletest/include/gtest/internal/gtest-port.h | 3 ++- googletest/test/googletest-catch-exceptions-test_.cc | 3 ++- googletest/test/googletest-param-test-invalid-name1-test.py | 9 +-------- googletest/test/googletest-param-test-invalid-name2-test.py | 9 +-------- googletest/test/googletest-param-test2-test.cc | 11 ++++++----- googletest/test/googletest-test2_test.cc | 11 ++++++----- 7 files changed, 20 insertions(+), 29 deletions(-) diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index 6182159..32ab534 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.cc @@ -37,7 +37,8 @@ // causes a link error when _tmain is defined in a static library and UNICODE // is enabled. For this reason instead of _tmain, main function is used on // Windows. See the following link to track the current status of this bug: -// https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library // NOLINT +// https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library +// // NOLINT #if GTEST_OS_WINDOWS_MOBILE # include // NOLINT diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 3edfa7f..0a25ef3 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -381,7 +381,8 @@ #if GTEST_LANG_CXX11 # define GTEST_HAS_STD_TUPLE_ 1 # if defined(__clang__) -// Inspired by https://clang.llvm.org/docs/LanguageExtensions.html#include-file-checking-macros +// Inspired by +// https://clang.llvm.org/docs/LanguageExtensions.html#include-file-checking-macros # if defined(__has_include) && !__has_include() # undef GTEST_HAS_STD_TUPLE_ # endif diff --git a/googletest/test/googletest-catch-exceptions-test_.cc b/googletest/test/googletest-catch-exceptions-test_.cc index cb018f9..6aac625 100644 --- a/googletest/test/googletest-catch-exceptions-test_.cc +++ b/googletest/test/googletest-catch-exceptions-test_.cc @@ -30,7 +30,8 @@ // 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 googletest-catch-exceptions-test.py. +// exceptions, and the output is verified by +// googletest-catch-exceptions-test.py. #include "gtest/gtest.h" diff --git a/googletest/test/googletest-param-test-invalid-name1-test.py b/googletest/test/googletest-param-test-invalid-name1-test.py index 63be043..a402c33 100644 --- a/googletest/test/googletest-param-test-invalid-name1-test.py +++ b/googletest/test/googletest-param-test-invalid-name1-test.py @@ -32,14 +32,7 @@ __author__ = 'jmadill@google.com (Jamie Madill)' -import os - -IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' - -if IS_LINUX: - import gtest_test_utils -else: - import gtest_test_utils +import gtest_test_utils binary_name = 'googletest-param-test-invalid-name1-test_' COMMAND = gtest_test_utils.GetTestExecutablePath(binary_name) diff --git a/googletest/test/googletest-param-test-invalid-name2-test.py b/googletest/test/googletest-param-test-invalid-name2-test.py index b1a80c1..5766134 100644 --- a/googletest/test/googletest-param-test-invalid-name2-test.py +++ b/googletest/test/googletest-param-test-invalid-name2-test.py @@ -32,14 +32,7 @@ __author__ = 'jmadill@google.com (Jamie Madill)' -import os - -IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' - -if IS_LINUX: - import gtest_test_utils -else: - import gtest_test_utils +import gtest_test_utils binary_name = 'googletest-param-test-invalid-name2-test_' COMMAND = gtest_test_utils.GetTestExecutablePath(binary_name) diff --git a/googletest/test/googletest-param-test2-test.cc b/googletest/test/googletest-param-test2-test.cc index c0a908b..c6e3d1f 100644 --- a/googletest/test/googletest-param-test2-test.cc +++ b/googletest/test/googletest-param-test2-test.cc @@ -44,17 +44,18 @@ using ::testing::internal::ParamGenerator; ParamGenerator extern_gen = Values(33); // Tests that a parameterized test case can be defined in one translation unit -// and instantiated in another. The test is defined in googletest-param-test-test.cc -// and ExternalInstantiationTest fixture class is defined in -// gtest-param-test_test.h. +// and instantiated in another. The test is defined in +// googletest-param-test-test.cc and ExternalInstantiationTest fixture class is +// defined in gtest-param-test_test.h. INSTANTIATE_TEST_CASE_P(MultiplesOf33, ExternalInstantiationTest, Values(33, 66)); // Tests that a parameterized test case can be instantiated // in multiple translation units. Another instantiation is defined -// in googletest-param-test-test.cc and InstantiationInMultipleTranslaionUnitsTest -// fixture is defined in gtest-param-test_test.h +// in googletest-param-test-test.cc and +// InstantiationInMultipleTranslaionUnitsTest fixture is defined in +// gtest-param-test_test.h INSTANTIATE_TEST_CASE_P(Sequence2, InstantiationInMultipleTranslaionUnitsTest, Values(42*3, 42*4, 42*5)); diff --git a/googletest/test/googletest-test2_test.cc b/googletest/test/googletest-test2_test.cc index e50c259..0a758c7 100644 --- a/googletest/test/googletest-test2_test.cc +++ b/googletest/test/googletest-test2_test.cc @@ -44,17 +44,18 @@ using ::testing::internal::ParamGenerator; ParamGenerator extern_gen_2 = Values(33); // Tests that a parameterized test case can be defined in one translation unit -// and instantiated in another. The test is defined in googletest-param-test-test.cc -// and ExternalInstantiationTest fixture class is defined in -// gtest-param-test_test.h. +// and instantiated in another. The test is defined in +// googletest-param-test-test.cc and ExternalInstantiationTest fixture class is +// defined in gtest-param-test_test.h. INSTANTIATE_TEST_CASE_P(MultiplesOf33, ExternalInstantiationTest, Values(33, 66)); // Tests that a parameterized test case can be instantiated // in multiple translation units. Another instantiation is defined -// in googletest-param-test-test.cc and InstantiationInMultipleTranslaionUnitsTest -// fixture is defined in gtest-param-test_test.h +// in googletest-param-test-test.cc and +// InstantiationInMultipleTranslaionUnitsTest fixture is defined in +// gtest-param-test_test.h INSTANTIATE_TEST_CASE_P(Sequence2, InstantiationInMultipleTranslaionUnitsTest, Values(42*3, 42*4, 42*5)); -- cgit v0.12 From 41e82cadf42d59c258473883073cdb4334abbc59 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Tue, 7 Aug 2018 14:05:42 -0400 Subject: upsream additional printer test --- googletest/test/googletest-printers-test.cc | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index 1b1026e..74825fc 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -1731,6 +1731,21 @@ TEST(PrintOptionalTest, Basic) { EXPECT_EQ("(1.1)", PrintToString(absl::optional{1.1})); EXPECT_EQ("(\"A\")", PrintToString(absl::optional{"A"})); } + +struct NonPrintable { + unsigned char contents = 17; +}; + +TEST(PrintOneofTest, Basic) { + using Type = absl::variant; + EXPECT_EQ("('int' with value 7)", PrintToString(Type(7))); + EXPECT_EQ("('StreamableInGlobal' with value StreamableInGlobal)", + PrintToString(Type(StreamableInGlobal{}))); + EXPECT_EQ( + "('testing::gtest_printers_test::NonPrintable' with value 1-byte object " + "<11>)", + PrintToString(Type(NonPrintable{}))); +} #endif // GTEST_HAS_ABSL } // namespace gtest_printers_test -- cgit v0.12 From 07d45437f288e25db9f7c78ecbc4df8b5b81a47b Mon Sep 17 00:00:00 2001 From: Wez Date: Tue, 7 Aug 2018 16:53:10 -0700 Subject: Fix typo breaking Fuchsia build --- googletest/src/gtest-death-test.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 8ae9968..1cdfa2e 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -900,7 +900,7 @@ int FuchsiaDeathTest::Wait() { } else { // Process terminated. GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type)); - GTEST_DEATH_TEST_CHECK_(packet.observed & ZX_PROCESS_TERMINATED); + GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED); } ReadAndInterpretStatusByte(); -- cgit v0.12 From bdf5fd3a98942f57385c8977dab965874d3c5d53 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 8 Aug 2018 13:20:02 -0400 Subject: Merge branch 'master' of https://github.com/google/googletest Formatting changes and code sync Merge branch 'master' of https://github.com/google/googletest --- googletest/src/gtest-death-test.cc | 5 ++++- googletest/src/gtest.cc | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 8ae9968..564bcd2 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -237,6 +237,9 @@ static std::string DeathTestThreadWarning(size_t thread_count) { msg << "couldn't detect the number of threads."; else msg << "detected " << thread_count << " threads."; + msg << " See https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#death-tests-and-threads" + << " for more explanation and suggested solutions, especially if" + << " this is the last message you see before your test times out."; return msg.GetString(); } # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA @@ -900,7 +903,7 @@ int FuchsiaDeathTest::Wait() { } else { // Process terminated. GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type)); - GTEST_DEATH_TEST_CHECK_(packet.observed & ZX_PROCESS_TERMINATED); + GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED); } ReadAndInterpretStatusByte(); diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 9c25c99..bc66c97 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -3138,6 +3138,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationStart( "Note: Randomizing tests' orders with a seed of %d .\n", unit_test.random_seed()); } + ColoredPrintf(COLOR_GREEN, "[==========] "); printf("Running %s from %s.\n", FormatTestCount(unit_test.test_to_run_count()).c_str(), -- cgit v0.12 From 0eeb1afcac5b4ef484533a695eb499c6f8ec9261 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 8 Aug 2018 14:41:21 -0400 Subject: code management changes, no functionalty changes --- googletest/include/gtest/gtest-death-test.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h index 8add8c0..59795e3 100644 --- a/googletest/include/gtest/gtest-death-test.h +++ b/googletest/include/gtest/gtest-death-test.h @@ -100,6 +100,7 @@ GTEST_API_ bool InDeathTestChild(); // // On the regular expressions used in death tests: // +// GOOGLETEST_CM0005 DO NOT DELETE // On POSIX-compliant systems (*nix), we use the library, // which uses the POSIX extended regex syntax. // @@ -202,6 +203,7 @@ class GTEST_API_ ExitedWithCode { # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // Tests that an exit code describes an exit due to termination by a // given signal. +// GOOGLETEST_CM0006 DO NOT DELETE class GTEST_API_ KilledBySignal { public: explicit KilledBySignal(int signum); -- cgit v0.12 From 00fc0d24d165516f5802c653e13ed9aa55326571 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 8 Aug 2018 15:14:21 -0400 Subject: Formatting tweaks, no functionality changes --- .../test/googletest-catch-exceptions-test_.cc | 4 ++-- googletest/test/googletest-env-var-test_.cc | 3 +-- googletest/test/googletest-linked-ptr-test.cc | 4 ++-- googletest/test/googletest-listener-test.cc | 3 ++- googletest/test/googletest-param-test2-test.cc | 2 +- googletest/test/googletest-port-test.cc | 3 +-- googletest/test/googletest-printers-test.cc | 3 +-- googletest/test/gtest-typed-test2_test.cc | 2 +- googletest/test/gtest-typed-test_test.cc | 2 +- googletest/test/gtest_all_test.cc | 24 +++++++++++----------- 10 files changed, 24 insertions(+), 26 deletions(-) diff --git a/googletest/test/googletest-catch-exceptions-test_.cc b/googletest/test/googletest-catch-exceptions-test_.cc index 6aac625..af2676b 100644 --- a/googletest/test/googletest-catch-exceptions-test_.cc +++ b/googletest/test/googletest-catch-exceptions-test_.cc @@ -33,11 +33,11 @@ // exceptions, and the output is verified by // googletest-catch-exceptions-test.py. -#include "gtest/gtest.h" - #include // NOLINT #include // For exit(). +#include "gtest/gtest.h" + #if GTEST_HAS_SEH # include #endif diff --git a/googletest/test/googletest-env-var-test_.cc b/googletest/test/googletest-env-var-test_.cc index 74b9506..4fba7a6 100644 --- a/googletest/test/googletest-env-var-test_.cc +++ b/googletest/test/googletest-env-var-test_.cc @@ -32,10 +32,9 @@ // A helper program for testing that Google Test parses the environment // variables correctly. -#include "gtest/gtest.h" - #include +#include "gtest/gtest.h" #include "src/gtest-internal-inl.h" using ::std::cout; diff --git a/googletest/test/googletest-linked-ptr-test.cc b/googletest/test/googletest-linked-ptr-test.cc index 6fcf512..d80ac1e 100644 --- a/googletest/test/googletest-linked-ptr-test.cc +++ b/googletest/test/googletest-linked-ptr-test.cc @@ -30,9 +30,9 @@ // Authors: Dan Egnor (egnor@google.com) // Ported to Windows: Vadim Berman (vadimb@google.com) -#include "gtest/internal/gtest-linked_ptr.h" - #include + +#include "gtest/internal/gtest-linked_ptr.h" #include "gtest/gtest.h" namespace { diff --git a/googletest/test/googletest-listener-test.cc b/googletest/test/googletest-listener-test.cc index 639529c..b01417a 100644 --- a/googletest/test/googletest-listener-test.cc +++ b/googletest/test/googletest-listener-test.cc @@ -33,9 +33,10 @@ // This file verifies Google Test event listeners receive events at the // right times. -#include "gtest/gtest.h" #include +#include "gtest/gtest.h" + using ::testing::AddGlobalTestEnvironment; using ::testing::Environment; using ::testing::InitGoogleTest; diff --git a/googletest/test/googletest-param-test2-test.cc b/googletest/test/googletest-param-test2-test.cc index c6e3d1f..c562ff0 100644 --- a/googletest/test/googletest-param-test2-test.cc +++ b/googletest/test/googletest-param-test2-test.cc @@ -33,7 +33,7 @@ // Google Test work. #include "gtest/gtest.h" -#include "googletest-param-test-test.h" +#include "test/googletest-param-test-test.h" using ::testing::Values; using ::testing::internal::ParamGenerator; diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc index 15a629f..32e893f 100644 --- a/googletest/test/googletest-port-test.cc +++ b/googletest/test/googletest-port-test.cc @@ -30,11 +30,10 @@ // Authors: vladl@google.com (Vlad Losev), wan@google.com (Zhanyong Wan) // // This file tests the internal cross-platform support utilities. +#include #include "gtest/internal/gtest-port.h" -#include - #if GTEST_OS_MAC # include #endif // GTEST_OS_MAC diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index 74825fc..4018863 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -33,8 +33,6 @@ // // This file tests the universal value printer. -#include "gtest/gtest-printers.h" - #include #include #include @@ -48,6 +46,7 @@ #include #include +#include "gtest/gtest-printers.h" #include "gtest/gtest.h" #if GTEST_HAS_UNORDERED_MAP_ diff --git a/googletest/test/gtest-typed-test2_test.cc b/googletest/test/gtest-typed-test2_test.cc index ad77c65..c284700 100644 --- a/googletest/test/gtest-typed-test2_test.cc +++ b/googletest/test/gtest-typed-test2_test.cc @@ -31,7 +31,7 @@ #include -#include "gtest-typed-test_test.h" +#include "test/gtest-typed-test_test.h" #include "gtest/gtest.h" #if GTEST_HAS_TYPED_TEST_P diff --git a/googletest/test/gtest-typed-test_test.cc b/googletest/test/gtest-typed-test_test.cc index 5e1b7b2..93628ba 100644 --- a/googletest/test/gtest-typed-test_test.cc +++ b/googletest/test/gtest-typed-test_test.cc @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) -#include "gtest-typed-test_test.h" +#include "test/gtest-typed-test_test.h" #include #include diff --git a/googletest/test/gtest_all_test.cc b/googletest/test/gtest_all_test.cc index 656066d..a9aba01 100644 --- a/googletest/test/gtest_all_test.cc +++ b/googletest/test/gtest_all_test.cc @@ -33,15 +33,15 @@ // // Sometimes it's desirable to build most of Google Test's own tests // by compiling a single file. This file serves this purpose. -#include "googletest-filepath-test.cc" -#include "googletest-linked-ptr-test.cc" -#include "googletest-message-test.cc" -#include "googletest-options-test.cc" -#include "googletest-port-test.cc" -#include "gtest_pred_impl_unittest.cc" -#include "gtest_prod_test.cc" -#include "googletest-test-part-test.cc" -#include "gtest-typed-test_test.cc" -#include "gtest-typed-test2_test.cc" -#include "gtest_unittest.cc" -#include "production.cc" +#include "test/googletest-filepath-test.cc" +#include "test/googletest-linked-ptr-test.cc" +#include "test/googletest-message-test.cc" +#include "test/googletest-options-test.cc" +#include "test/googletest-port-test.cc" +#include "test/gtest_pred_impl_unittest.cc" +#include "test/gtest_prod_test.cc" +#include "test/googletest-test-part-test.cc" +#include "test/gtest-typed-test_test.cc" +#include "test/gtest-typed-test2_test.cc" +#include "test/gtest_unittest.cc" +#include "test/production.cc" -- cgit v0.12 From db43df6df733c3b6c8a0a049e2000bb9869c5a8a Mon Sep 17 00:00:00 2001 From: Wiktor Garbacz Date: Thu, 9 Aug 2018 13:14:36 +0200 Subject: docs: fix broken links --- googletest/docs/advanced.md | 4 ++-- googletest/docs/faq.md | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index feb8ad6..ffd9480 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -3,7 +3,7 @@ ## Introduction -Now that you have read the [googletest Primer](primer) and learned how to write +Now that you have read the [googletest Primer](primer.md) and learned how to write tests using googletest, it's time to learn some new tricks. This document will show you more assertions as well as how to construct complex failure messages, propagate fatal failures, reuse and speed up your test fixtures, and use various @@ -152,7 +152,7 @@ c is 10 > > 1. If you see a compiler error "no matching function to call" when using > `ASSERT_PRED*` or `EXPECT_PRED*`, please see -> [this](faq#OverloadedPredicate) for how to resolve it. +> [this](faq.md#OverloadedPredicate) for how to resolve it. > 1. Currently we only provide predicate assertions of arity <= 5. If you need > a higher-arity assertion, let [us](https://github.com/google/googletest/issues) know. diff --git a/googletest/docs/faq.md b/googletest/docs/faq.md index d613f7b..7d42ff7 100644 --- a/googletest/docs/faq.md +++ b/googletest/docs/faq.md @@ -707,8 +707,9 @@ In general, the recommended way to cause the code to behave differently under test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject different functionality from the test and from the production code. Since your production code doesn't link in the for-test logic at all (the -[`testonly`](http://go/testonly) attribute for BUILD targets helps to ensure -that), there is no danger in accidentally running it. +[`testonly`](https://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) +attribute for BUILD targets helps to ensure that), there is no danger in +accidentally running it. However, if you *really*, *really*, *really* have no choice, and if you follow the rule of ending your test program names with `_test`, you can use the -- cgit v0.12 From 063a90b391d475f8f7ddc12e1df3dabcaf643f79 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 9 Aug 2018 10:51:49 -0400 Subject: Formatting change for auto code management, no functionality changes Merge branch 'master' of https://github.com/google/googletest --- googlemock/test/gmock_output_test.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/googlemock/test/gmock_output_test.py b/googlemock/test/gmock_output_test.py index 8f57d46..c8af0f9 100755 --- a/googlemock/test/gmock_output_test.py +++ b/googlemock/test/gmock_output_test.py @@ -33,9 +33,10 @@ To update the golden file: gmock_output_test.py --build_dir=BUILD/DIR --gengolden -# where BUILD/DIR contains the built gmock_output_test_ file. +where BUILD/DIR contains the built gmock_output_test_ file. gmock_output_test.py --gengolden gmock_output_test.py + """ __author__ = 'wan@google.com (Zhanyong Wan)' -- cgit v0.12 From ecc6944fb127be957185731e1dfbfd6eafb02d0e Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 9 Aug 2018 11:12:12 -0400 Subject: Fixing identation, causes build errors when warnings are treated as errors --- googletest/src/gtest-death-test.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 564bcd2..2214118 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -238,8 +238,8 @@ static std::string DeathTestThreadWarning(size_t thread_count) { else msg << "detected " << thread_count << " threads."; msg << " See https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#death-tests-and-threads" - << " for more explanation and suggested solutions, especially if" - << " this is the last message you see before your test times out."; + << " for more explanation and suggested solutions, especially if" + << " this is the last message you see before your test times out."; return msg.GetString(); } # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA -- cgit v0.12 From d5b31df900802ba2651ebd51dfb1a0f83edae860 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 9 Aug 2018 11:33:42 -0400 Subject: Update gtest-death-test.cc --- googletest/src/gtest-death-test.cc | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 2214118..9735df1 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -233,16 +233,18 @@ static std::string DeathTestThreadWarning(size_t thread_count) { Message msg; msg << "Death tests use fork(), which is unsafe particularly" << " in a threaded context. For this test, " << GTEST_NAME_ << " "; - if (thread_count == 0) + if (thread_count == 0) { msg << "couldn't detect the number of threads."; - else + } else { msg << "detected " << thread_count << " threads."; - msg << " See https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#death-tests-and-threads" - << " for more explanation and suggested solutions, especially if" - << " this is the last message you see before your test times out."; + } + msg << " See " + "https://github.com/google/googletest/blob/master/googletest/docs/" + "advanced.md#death-tests-and-threads" + << " for more explanation and suggested solutions, especially if" + << " this is the last message you see before your test times out."; return msg.GetString(); -} -# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +}# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // Flag characters for reporting a death test that did not die. static const char kDeathTestLived = 'L'; -- cgit v0.12 From f7042937af1b684c02145b0ddc6909e387caa81e Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 9 Aug 2018 11:53:45 -0400 Subject: Fixing identation, causes build errors when warnings are treated as errors --- googletest/src/gtest-death-test.cc | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 2214118..854bc46 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -233,13 +233,16 @@ static std::string DeathTestThreadWarning(size_t thread_count) { Message msg; msg << "Death tests use fork(), which is unsafe particularly" << " in a threaded context. For this test, " << GTEST_NAME_ << " "; - if (thread_count == 0) + if (thread_count == 0) { msg << "couldn't detect the number of threads."; - else + } else { msg << "detected " << thread_count << " threads."; - msg << " See https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#death-tests-and-threads" - << " for more explanation and suggested solutions, especially if" - << " this is the last message you see before your test times out."; + } + msg << " See " + "https://github.com/google/googletest/blob/master/googletest/docs/" + "advanced.md#death-tests-and-threads" + << " for more explanation and suggested solutions, especially if" + << " this is the last message you see before your test times out."; return msg.GetString(); } # endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA -- cgit v0.12 From 7a79459a663ce98a31fdbb14dea9a750bc285885 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 9 Aug 2018 11:55:48 -0400 Subject: Fixing identation, causes build errors when warnings are treated as errors --- googletest/src/gtest-death-test.cc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 9735df1..854bc46 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -244,7 +244,8 @@ static std::string DeathTestThreadWarning(size_t thread_count) { << " for more explanation and suggested solutions, especially if" << " this is the last message you see before your test times out."; return msg.GetString(); -}# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA +} +# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA // Flag characters for reporting a death test that did not die. static const char kDeathTestLived = 'L'; -- cgit v0.12 From 4d9411467dafe438a4ef04befed5ae3ae14f931a Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 9 Aug 2018 12:21:49 -0400 Subject: code management comments, [ci-skip], no functionality changes --- googletest/include/gtest/internal/gtest-port.h | 2 ++ googletest/src/gtest.cc | 1 + 2 files changed, 3 insertions(+) diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 0a25ef3..6fc9a80 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -180,6 +180,7 @@ // GTEST_HAS_TYPED_TEST - typed tests // GTEST_HAS_TYPED_TEST_P - type-parameterized tests // GTEST_IS_THREADSAFE - Google Test is thread-safe. +// GOOGLETEST_CM0007 DO NOT DELETE // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with // GTEST_HAS_POSIX_RE (see above) which users can // define themselves. @@ -231,6 +232,7 @@ // Regular expressions: // RE - a simple regular expression class using the POSIX // Extended Regular Expression syntax on UNIX-like platforms +// GOOGLETEST_CM0008 DO NOT DELETE // or a reduced regular exception syntax on other // platforms, including Windows. // Logging: diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index bc66c97..2ec36fa 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -3590,6 +3590,7 @@ std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( // The following routines generate an XML representation of a UnitTest // object. +// GOOGLETEST_CM0009 DO NOT DELETE // // This is how Google Test concepts map to the DTD: // -- cgit v0.12 From acaf5beaccf6cededfb741a1e67df0a497738265 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 9 Aug 2018 13:37:11 -0400 Subject: formatting and small changes related to code management, no functionality changes --- googletest/test/googletest-output-test.py | 11 +++++------ googletest/test/gtest_test_utils.py | 8 +++----- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/googletest/test/googletest-output-test.py b/googletest/test/googletest-output-test.py index c1c3652..0dae8d1 100755 --- a/googletest/test/googletest-output-test.py +++ b/googletest/test/googletest-output-test.py @@ -31,12 +31,11 @@ """Tests the text output of Google C++ Testing and Mocking Framework. - -SYNOPSIS - googletest_output_test.py --build_dir=BUILD/DIR --gengolden - # where BUILD/DIR contains the built googletest-output-test_ file. - googletest_output_test.py --gengolden - googletest_output_test.py +To update the golden file: +googletest_output_test.py --build_dir=BUILD/DIR --gengolden +where BUILD/DIR contains the built googletest-output-test_ file. +googletest_output_test.py --gengolden +googletest_output_test.py """ __author__ = 'wan@google.com (Zhanyong Wan)' diff --git a/googletest/test/gtest_test_utils.py b/googletest/test/gtest_test_utils.py index d7fc099..c4c0227 100755 --- a/googletest/test/gtest_test_utils.py +++ b/googletest/test/gtest_test_utils.py @@ -36,15 +36,13 @@ __author__ = 'wan@google.com (Zhanyong Wan)' import os import sys -IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' IS_WINDOWS = os.name == 'nt' IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0] import atexit import shutil import tempfile -import unittest -_test_module = unittest +import unittest as _test_module try: import subprocess @@ -74,7 +72,7 @@ def SetEnvVar(env_var, value): # Here we expose a class from a particular module, depending on the # environment. The comment suppresses the 'Invalid variable name' lint # complaint. -TestCase = _test_module.TestCase # pylint: disable-msg=C6409 +TestCase = _test_module.TestCase # pylint: disable=C6409 # Initially maps a flag to its default value. After # _ParseAndStripGTestFlags() is called, maps a flag to its actual value. @@ -88,7 +86,7 @@ def _ParseAndStripGTestFlags(argv): # Suppresses the lint complaint about a global variable since we need it # here to maintain module-wide state. - global _gtest_flags_are_parsed # pylint: disable-msg=W0603 + global _gtest_flags_are_parsed # pylint: disable=W0603 if _gtest_flags_are_parsed: return -- cgit v0.12 From 5eb263569bc1f90ff3820c4f9f5fbc8fa25a031f Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 9 Aug 2018 15:24:43 -0400 Subject: Update gmock_output_test.py --- googlemock/test/gmock_output_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemock/test/gmock_output_test.py b/googlemock/test/gmock_output_test.py index c8af0f9..20323e1 100755 --- a/googlemock/test/gmock_output_test.py +++ b/googlemock/test/gmock_output_test.py @@ -29,7 +29,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. -"""Tests the text output of Google C++ Mocking Framework. +r"""Tests the text output of Google C++ Mocking Framework. To update the golden file: gmock_output_test.py --build_dir=BUILD/DIR --gengolden -- cgit v0.12 From e821a2db235e67a66d9a88ea5c27316eb8d30cb7 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 10 Aug 2018 10:59:52 -0400 Subject: Update README.md --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index d87abce..7ca381e 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,13 @@ [![Build Status](https://travis-ci.org/google/googletest.svg?branch=master)](https://travis-ci.org/google/googletest) [![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master) +**Future Plans**: +* Tagged Release 1.8.x. +** The 1.8.x will be the last release that works with pre-C++11 compilers. The 1.8.1 will not accept any requests for any new features and any bugfix requests will only be accepted if proven "critical" +* Post 1.8.x - work to remove C++98 support / cleanup code in the master branch. When this work is completed there will be a 1.9.0 tagged release +* Post 1.9.0 googletest will follow [Abseil Live at Head philosophy](https://abseil.io/about/philosophy) + + Welcome to **Google Test**, Google's C++ test framework! This repository is a merger of the formerly separate GoogleTest and -- cgit v0.12 From 945618b2025b8f0b73f374f4b258e5df85c784a2 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 10 Aug 2018 11:06:52 -0400 Subject: Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7ca381e..d2f98ae 100644 --- a/README.md +++ b/README.md @@ -7,8 +7,8 @@ **Future Plans**: * Tagged Release 1.8.x. ** The 1.8.x will be the last release that works with pre-C++11 compilers. The 1.8.1 will not accept any requests for any new features and any bugfix requests will only be accepted if proven "critical" -* Post 1.8.x - work to remove C++98 support / cleanup code in the master branch. When this work is completed there will be a 1.9.0 tagged release -* Post 1.9.0 googletest will follow [Abseil Live at Head philosophy](https://abseil.io/about/philosophy) +* Post 1.8.x - work to remove C++98 support / cleanup code in the master branch. When this work is completed there will be a 1.9.x tagged release +* Post 1.9.x googletest will follow [Abseil Live at Head philosophy](https://abseil.io/about/philosophy) Welcome to **Google Test**, Google's C++ test framework! -- cgit v0.12 From 4de527dc2cc28074513eea77495909de22df633a Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 10 Aug 2018 11:29:18 -0400 Subject: Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d2f98ae..90ea02c 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ **Future Plans**: * Tagged Release 1.8.x. ** The 1.8.x will be the last release that works with pre-C++11 compilers. The 1.8.1 will not accept any requests for any new features and any bugfix requests will only be accepted if proven "critical" -* Post 1.8.x - work to remove C++98 support / cleanup code in the master branch. When this work is completed there will be a 1.9.x tagged release +* Post 1.8.x - work to improve/cleanup/pay technical debt. When this work is completed there will be a 1.9.x tagged release * Post 1.9.x googletest will follow [Abseil Live at Head philosophy](https://abseil.io/about/philosophy) -- cgit v0.12 From 77ac31c35f15980d9b54931404a4ada3285abead Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 10 Aug 2018 11:30:04 -0400 Subject: Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 90ea02c..8e343d2 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ **Future Plans**: * Tagged Release 1.8.x. -** The 1.8.x will be the last release that works with pre-C++11 compilers. The 1.8.1 will not accept any requests for any new features and any bugfix requests will only be accepted if proven "critical" +The 1.8.x will be the last release that works with pre-C++11 compilers. The 1.8.1 will not accept any requests for any new features and any bugfix requests will only be accepted if proven "critical" * Post 1.8.x - work to improve/cleanup/pay technical debt. When this work is completed there will be a 1.9.x tagged release * Post 1.9.x googletest will follow [Abseil Live at Head philosophy](https://abseil.io/about/philosophy) -- cgit v0.12 From b1236528fef2feba22cb0c8b371df8686e801456 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 10 Aug 2018 12:05:17 -0400 Subject: Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8e343d2..4886c92 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master) **Future Plans**: -* Tagged Release 1.8.x. +* 1.8.x Release The 1.8.x will be the last release that works with pre-C++11 compilers. The 1.8.1 will not accept any requests for any new features and any bugfix requests will only be accepted if proven "critical" * Post 1.8.x - work to improve/cleanup/pay technical debt. When this work is completed there will be a 1.9.x tagged release * Post 1.9.x googletest will follow [Abseil Live at Head philosophy](https://abseil.io/about/philosophy) -- cgit v0.12 From 8cccb2a718c3fbfa1742b0badd50b81f75de678e Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 10 Aug 2018 15:20:51 -0400 Subject: Update README.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 4886c92..14a9e23 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,7 @@ [![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master) **Future Plans**: -* 1.8.x Release -The 1.8.x will be the last release that works with pre-C++11 compilers. The 1.8.1 will not accept any requests for any new features and any bugfix requests will only be accepted if proven "critical" +* 1.8.x Release - the 1.8.x will be the last release that works with pre-C++11 compilers. The 1.8.1 will not accept any requests for any new features and any bugfix requests will only be accepted if proven "critical" * Post 1.8.x - work to improve/cleanup/pay technical debt. When this work is completed there will be a 1.9.x tagged release * Post 1.9.x googletest will follow [Abseil Live at Head philosophy](https://abseil.io/about/philosophy) -- cgit v0.12 From 390a6b79321757ca91544228f22ae9eb81ede44e Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 10 Aug 2018 15:42:16 -0400 Subject: Mode change on a python script --- googletest/test/gtest_testbridge_test.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 googletest/test/gtest_testbridge_test.py diff --git a/googletest/test/gtest_testbridge_test.py b/googletest/test/gtest_testbridge_test.py old mode 100644 new mode 100755 -- cgit v0.12 From ecc241900a1eae04d4b5f642cb8b3ebfc497d5e7 Mon Sep 17 00:00:00 2001 From: Yi Zheng Date: Mon, 13 Aug 2018 17:57:51 +0800 Subject: - Fix the broken markdown table - Fix some format issue --- googletest/docs/advanced.md | 94 +++++++++++++++++++-------------------------- 1 file changed, 39 insertions(+), 55 deletions(-) diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index ffd9480..0a92e52 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -103,13 +103,11 @@ If you already have a function or functor that returns `bool` (or a type that can be implicitly converted to `bool`), you can use it in a *predicate assertion* to get the function arguments printed for free: -| Fatal assertion | Nonfatal assertion | Verifies | -| -------------------- | -------------------- | --------------------------- | -| `ASSERT_PRED1(pred1, | `EXPECT_PRED1(pred1, | `pred1(val1)` is true | -: val1);` : val1);` : : -| `ASSERT_PRED2(pred2, | `EXPECT_PRED2(pred2, | `pred2(val1, val2)` is true | -: val1, val2);` : val1, val2);` : : -| `...` | `...` | ... | +| Fatal assertion | Nonfatal assertion | Verifies | +| ---------------------------------- | ---------------------------------- | --------------------------- | +| `ASSERT_PRED1(pred1, val1);` | `EXPECT_PRED1(pred1, val1);` | `pred1(val1)` is true | +| `ASSERT_PRED2(pred2, val1, val2);` | `EXPECT_PRED2(pred2, val1, val2);` | `pred2(val1, val2)` is true | +| `...` | `...` | ... | In the above, `predn` is an `n`-ary predicate function or functor, where `val1`, `val2`, ..., and `valn` are its arguments. The assertion succeeds if the @@ -120,7 +118,7 @@ either case, the arguments are evaluated exactly once. Here's an example. Given ```c++ -// Returns true iff m and n have no common divisors except 1. +// Returns true if m and n have no common divisors except 1. bool MutuallyPrime(int m, int n) { ... } const int a = 3; @@ -339,12 +337,10 @@ want to learn more, see #### Floating-Point Macros -| Fatal assertion | Nonfatal assertion | Verifies | -| ----------------------- | ----------------------- | ----------------------- | -| `ASSERT_FLOAT_EQ(val1, | `EXPECT_FLOAT_EQ(val1, | the two `float` values | -: val2);` : val2);` : are almost equal : -| `ASSERT_DOUBLE_EQ(val1, | `EXPECT_DOUBLE_EQ(val1, | the two `double` values | -: val2);` : val2);` : are almost equal : +| Fatal assertion | Nonfatal assertion | Verifies | +| ------------------------------- | ------------------------------ | ---------------------------------------- | +| `ASSERT_FLOAT_EQ(val1, val2);` | `EXPECT_FLOAT_EQ(val1,val2);` | the two `float` values are almost equal | +| `ASSERT_DOUBLE_EQ(val1, val2);` | `EXPECT_DOUBLE_EQ(val1, val2);`| the two `double` values are almost equal | By "almost equal" we mean the values are within 4 ULP's from each other. @@ -354,12 +350,9 @@ unsafe and has been deprecated. Please don't use it any more. The following assertions allow you to choose the acceptable error bound: -| Fatal assertion | Nonfatal assertion | Verifies | -| ------------------ | ------------------------ | ------------------------- | -| `ASSERT_NEAR(val1, | `EXPECT_NEAR(val1, val2, | the difference between | -: val2, abs_error);` : abs_error);` : `val1` and `val2` doesn't : -: : : exceed the given absolute : -: : : error : +| Fatal assertion | Nonfatal assertion | Verifies | +| ------------------------------------- | ------------------------------------- | ------------------------- | +| `ASSERT_NEAR(val1, val2, abs_error);` | `EXPECT_NEAR(val1, val2, abs_error);` | the difference between `val1` and `val2` doesn't exceed the given absolute error | **Availability**: Linux, Windows, Mac. @@ -387,10 +380,9 @@ library of matchers for validating arguments passed to mock objects. A gMock *matcher* is basically a predicate that knows how to describe itself. It can be used in these assertion macros: -| Fatal assertion | Nonfatal assertion | Verifies | -| ------------------- | ------------------------------ | --------------------- | -| `ASSERT_THAT(value, | `EXPECT_THAT(value, matcher);` | value matches matcher | -: matcher);` : : : +| Fatal assertion | Nonfatal assertion | Verifies | +| ------------------------------ | ------------------------------ | --------------------- | +| `ASSERT_THAT(value, matcher);` | `EXPECT_THAT(value, matcher);` | value matches matcher | For example, `StartsWith(prefix)` is a matcher that matches a string starting with `prefix`, and you can write: @@ -1396,17 +1388,11 @@ namespace: | Parameter Generator | Behavior | | ---------------------------- | ------------------------------------------- | -| `Range(begin, end [, step])` | Yields values `{begin, begin+step, | -: : begin+step+step, ...}`. The values do not : -: : include `end`. `step` defaults to 1. : +| `Range(begin, end [, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | | `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | -| `ValuesIn(container)` and | Yields values from a C-style array, an | -: `ValuesIn(begin,end)` : STL-style container, or an iterator range : -: : `[begin, end)`. : +| `ValuesIn(container)` and `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. | | `Bool()` | Yields sequence `{false, true}`. | -| `Combine(g1, g2, ..., gN)` | Yields all combinations (Cartesian product) | -: : as std\:\:tuples of the values generated by : -: : the `N` generators. : +| `Combine(g1, g2, ..., gN)` | Yields all combinations (Cartesian product) as std\:\:tuples of the values generated by the `N` generators. | For more details, see the comments at the definitions of these functions. @@ -1726,11 +1712,11 @@ To test them, we use the following special techniques: ```c++ // foo.h -#include "gtest/gtest_prod.h" + #include "gtest/gtest_prod.h" class Foo { ... - private: + private: FRIEND_TEST(FooTest, BarReturnsZeroOnNull); int Bar(void* x); @@ -1779,7 +1765,7 @@ To test them, we use the following special techniques: ``` - ## "Catching" Failures +## "Catching" Failures If you are building a testing utility on top of googletest, you'll want to test your utility. What framework would you use to test it? googletest, of course. @@ -2168,23 +2154,22 @@ random seed and re-shuffle the tests in each iteration. googletest can use colors in its terminal output to make it easier to spot the important information: -... -[----------] 1 test from FooTest -[ RUN ] FooTest.DoesAbc -[ OK ] FooTest.DoesAbc -[----------] 2 tests from BarTest -[ RUN ] BarTest.HasXyzProperty -[ OK ] BarTest.HasXyzProperty -[ RUN ] BarTest.ReturnsTrueOnSuccess -... some error messages ... -[ FAILED ] BarTest.ReturnsTrueOnSuccess -... -[==========] 30 tests from 14 test cases ran. -[ PASSED ] 28 tests. -[ FAILED ] 2 tests, listed below: -[ FAILED ] BarTest.ReturnsTrueOnSuccess -[ FAILED ] AnotherTest.DoesXyz - +...
+[----------] 1 test from FooTest
+[ RUN ] FooTest.DoesAbc
+[ OK ] FooTest.DoesAbc
+[----------] 2 tests from BarTest
+[ RUN ] BarTest.HasXyzProperty
+[ OK ] BarTest.HasXyzProperty
+[ RUN ] BarTest.ReturnsTrueOnSuccess
+... some error messages ...
+[ FAILED ] BarTest.ReturnsTrueOnSuccess
+...
+[==========] 30 tests from 14 test cases ran.
+[ PASSED ] 28 tests.
+[ FAILED ] 2 tests, listed below:
+[ FAILED ] BarTest.ReturnsTrueOnSuccess
+[ FAILED ] AnotherTest.DoesXyz
2 FAILED TESTS You can set the `GTEST_COLOR` environment variable or the `--gtest_color` @@ -2193,8 +2178,7 @@ disable colors, or let googletest decide. When the value is `auto`, googletest will use colors if and only if the output goes to a terminal and (on non-Windows platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`. -> -> **Availability**: Linux, Windows, Mac. + **Availability**: Linux, Windows, Mac. #### Suppressing the Elapsed Time -- cgit v0.12 From 18c940d13a58a3fa1016d2887e66bd1c73720e0f Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 13 Aug 2018 13:17:38 -0400 Subject: comment cleanup --- googlemock/include/gmock/internal/custom/gmock-matchers.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/googlemock/include/gmock/internal/custom/gmock-matchers.h b/googlemock/include/gmock/internal/custom/gmock-matchers.h index b9b7e3f..227d91f 100644 --- a/googlemock/include/gmock/internal/custom/gmock-matchers.h +++ b/googlemock/include/gmock/internal/custom/gmock-matchers.h @@ -31,8 +31,6 @@ // An installation-specific extension point for gmock-matchers.h. // ============================================================ // -// Adds google3 callback support to CallableTraits. - // GOOGLETEST_CM0002 DO NOT DELETE #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ -- cgit v0.12 From 63baab8924f589fdfd934ae24613e59f8d3ef635 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 13 Aug 2018 14:31:56 -0400 Subject: Move instructions into custom/README files --- googlemock/include/gmock/internal/custom/README.md | 16 +++++++ .../include/gmock/internal/custom/gmock-matchers.h | 4 +- .../include/gmock/internal/custom/gmock-port.h | 11 +---- googletest/include/gtest/internal/custom/README.md | 56 ++++++++++++++++++++++ .../include/gtest/internal/custom/gtest-port.h | 35 +------------- .../include/gtest/internal/custom/gtest-printers.h | 4 +- googletest/include/gtest/internal/custom/gtest.h | 10 +--- 7 files changed, 78 insertions(+), 58 deletions(-) create mode 100644 googlemock/include/gmock/internal/custom/README.md create mode 100644 googletest/include/gtest/internal/custom/README.md diff --git a/googlemock/include/gmock/internal/custom/README.md b/googlemock/include/gmock/internal/custom/README.md new file mode 100644 index 0000000..ef5f9bf --- /dev/null +++ b/googlemock/include/gmock/internal/custom/README.md @@ -0,0 +1,16 @@ +# Customization Points + +The custom directory is an injection point for custom user configurations. + +## Header gmock-port.h + +The following macros can be defined: + +### Flag related macros: + +* GMOCK_DECLARE_bool_(name) +* GMOCK_DECLARE_int32_(name) +* GMOCK_DECLARE_string_(name) +* GMOCK_DEFINE_bool_(name, default_val, doc) +* GMOCK_DEFINE_int32_(name, default_val, doc) +* GMOCK_DEFINE_string_(name, default_val, doc) diff --git a/googlemock/include/gmock/internal/custom/gmock-matchers.h b/googlemock/include/gmock/internal/custom/gmock-matchers.h index 227d91f..14aafaa 100644 --- a/googlemock/include/gmock/internal/custom/gmock-matchers.h +++ b/googlemock/include/gmock/internal/custom/gmock-matchers.h @@ -27,9 +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. // -// ============================================================ -// An installation-specific extension point for gmock-matchers.h. -// ============================================================ +// Injection point for custom user configurations. See README for details // // GOOGLETEST_CM0002 DO NOT DELETE diff --git a/googlemock/include/gmock/internal/custom/gmock-port.h b/googlemock/include/gmock/internal/custom/gmock-port.h index ad9ae36..0030fe9 100644 --- a/googlemock/include/gmock/internal/custom/gmock-port.h +++ b/googlemock/include/gmock/internal/custom/gmock-port.h @@ -27,16 +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. // -// Injection point for custom user configurations. -// The following macros can be defined: -// -// Flag related macros: -// GMOCK_DECLARE_bool_(name) -// GMOCK_DECLARE_int32_(name) -// GMOCK_DECLARE_string_(name) -// GMOCK_DEFINE_bool_(name, default_val, doc) -// GMOCK_DEFINE_int32_(name, default_val, doc) -// GMOCK_DEFINE_string_(name, default_val, doc) +// Injection point for custom user configurations. See README for details // // ** Custom implementation starts here ** diff --git a/googletest/include/gtest/internal/custom/README.md b/googletest/include/gtest/internal/custom/README.md new file mode 100644 index 0000000..e39b7c6 --- /dev/null +++ b/googletest/include/gtest/internal/custom/README.md @@ -0,0 +1,56 @@ +# Customization Points + +The custom directory is an injection point for custom user configurations. + +## Header gtest.h + +### The following macros can be defined: + +* GTEST_OS_STACK_TRACE_GETTER_ - The name of an implementation of + OsStackTraceGetterInterface. +* GTEST_CUSTOM_TEMPDIR_FUNCTION_ - An override for testing::TempDir(). See + testing::TempDir for semantics and signature. + +## Header gtest-port.h + +The following macros can be defined: + +### Flag related macros: + +* GTEST_FLAG(flag_name) +* GTEST_USE_OWN_FLAGFILE_FLAG_ - Define to 0 when the system provides its own + flagfile flag parsing. +* GTEST_DECLARE_bool_(name) +* GTEST_DECLARE_int32_(name) +* GTEST_DECLARE_string_(name) * +* GTEST_DEFINE_bool_(name, default_val, doc) +* GTEST_DEFINE_int32_(name, default_val, doc) +* GTEST_DEFINE_string_(name, default_val, doc) + +### Logging: + +* GTEST_LOG_(severity) +* GTEST_CHECK_(condition) +* Functions LogToStderr() and FlushInfoLog() have to be provided too. + +### Threading: + +* GTEST_HAS_NOTIFICATION_ - Enabled if Notification is already provided. +* GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Enabled if Mutex and ThreadLocal are + already provided. Must also provide GTEST_DECLARE_STATIC_MUTEX_(mutex) and + GTEST_DEFINE_STATIC_MUTEX_(mutex) +* GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) +* GTEST_LOCK_EXCLUDED_(locks) + +### Underlying library support features + +* GTEST_HAS_CXXABI_H_ + +### Exporting API symbols: + +* GTEST_API_ - Specifier for exported symbols. + +## Header gtest-printers.h + +* See documentation at gtest/gtest-printers.h for details on how to define a + custom printer. diff --git a/googletest/include/gtest/internal/custom/gtest-port.h b/googletest/include/gtest/internal/custom/gtest-port.h index aa5da29..cd85d95 100644 --- a/googletest/include/gtest/internal/custom/gtest-port.h +++ b/googletest/include/gtest/internal/custom/gtest-port.h @@ -27,40 +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. // -// Injection point for custom user configurations. -// The following macros can be defined: -// -// Flag related macros: -// GTEST_FLAG(flag_name) -// GTEST_USE_OWN_FLAGFILE_FLAG_ - Define to 0 when the system provides its -// own flagfile flag parsing. -// GTEST_DECLARE_bool_(name) -// GTEST_DECLARE_int32_(name) -// GTEST_DECLARE_string_(name) -// GTEST_DEFINE_bool_(name, default_val, doc) -// GTEST_DEFINE_int32_(name, default_val, doc) -// GTEST_DEFINE_string_(name, default_val, doc) -// -// Logging: -// GTEST_LOG_(severity) -// GTEST_CHECK_(condition) -// Functions LogToStderr() and FlushInfoLog() have to be provided too. -// -// Threading: -// GTEST_HAS_NOTIFICATION_ - Enabled if Notification is already provided. -// GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Enabled if Mutex and ThreadLocal are -// already provided. -// Must also provide GTEST_DECLARE_STATIC_MUTEX_(mutex) and -// GTEST_DEFINE_STATIC_MUTEX_(mutex) -// -// GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) -// GTEST_LOCK_EXCLUDED_(locks) -// -// Underlying library support features: -// GTEST_HAS_CXXABI_H_ -// -// Exporting API symbols: -// GTEST_API_ - Specifier for exported symbols. +// Injection point for custom user configurations. See README for details // // ** Custom implementation starts here ** diff --git a/googletest/include/gtest/internal/custom/gtest-printers.h b/googletest/include/gtest/internal/custom/gtest-printers.h index 60c1ea0..eb4467a 100644 --- a/googletest/include/gtest/internal/custom/gtest-printers.h +++ b/googletest/include/gtest/internal/custom/gtest-printers.h @@ -31,8 +31,8 @@ // installation of gTest. // It will be included from gtest-printers.h and the overrides in this file // will be visible to everyone. -// See documentation at gtest/gtest-printers.h for details on how to define a -// custom printer. +// +// Injection point for custom user configurations. See README for details // // ** Custom implementation starts here ** diff --git a/googletest/include/gtest/internal/custom/gtest.h b/googletest/include/gtest/internal/custom/gtest.h index 6f7c5e4..4c8e07b 100644 --- a/googletest/include/gtest/internal/custom/gtest.h +++ b/googletest/include/gtest/internal/custom/gtest.h @@ -27,15 +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. // -// Injection point for custom user configurations. -// The following macros can be defined: -// -// GTEST_OS_STACK_TRACE_GETTER_ - The name of an implementation of -// OsStackTraceGetterInterface. -// -// GTEST_CUSTOM_TEMPDIR_FUNCTION_ - An override for testing::TempDir(). -// See testing::TempDir for semantics and -// signature. +// Injection point for custom user configurations. See README for details // // ** Custom implementation starts here ** -- cgit v0.12 From 9ca399ae053d0a2a4d206fffe9ab76f577dbe22e Mon Sep 17 00:00:00 2001 From: Elias Daler Date: Mon, 13 Aug 2018 23:01:00 +0300 Subject: Change location of generated pkg-config files from CMAKE_BINARY_DIR to gmock/gtest_BINARY_DIR (#1717) --- googlemock/CMakeLists.txt | 6 +++--- googletest/CMakeLists.txt | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/googlemock/CMakeLists.txt b/googlemock/CMakeLists.txt index bac2e3b..0b1f77a 100644 --- a/googlemock/CMakeLists.txt +++ b/googlemock/CMakeLists.txt @@ -128,13 +128,13 @@ if(INSTALL_GMOCK) # configure and install pkgconfig files configure_file( cmake/gmock.pc.in - "${CMAKE_BINARY_DIR}/gmock.pc" + "${gmock_BINARY_DIR}/gmock.pc" @ONLY) configure_file( cmake/gmock_main.pc.in - "${CMAKE_BINARY_DIR}/gmock_main.pc" + "${gmock_BINARY_DIR}/gmock_main.pc" @ONLY) - install(FILES "${CMAKE_BINARY_DIR}/gmock.pc" "${CMAKE_BINARY_DIR}/gmock_main.pc" + install(FILES "${gmock_BINARY_DIR}/gmock.pc" "${gmock_BINARY_DIR}/gmock_main.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") endif() diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index ba2c2c2..6a917bb 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -121,13 +121,13 @@ if(INSTALL_GTEST) # configure and install pkgconfig files configure_file( cmake/gtest.pc.in - "${CMAKE_BINARY_DIR}/gtest.pc" + "${gtest_BINARY_DIR}/gtest.pc" @ONLY) configure_file( cmake/gtest_main.pc.in - "${CMAKE_BINARY_DIR}/gtest_main.pc" + "${gtest_BINARY_DIR}/gtest_main.pc" @ONLY) - install(FILES "${CMAKE_BINARY_DIR}/gtest.pc" "${CMAKE_BINARY_DIR}/gtest_main.pc" + install(FILES "${gtest_BINARY_DIR}/gtest.pc" "${gtest_BINARY_DIR}/gtest_main.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") endif() -- cgit v0.12 From 9060e19c87d6a041b3f31b172b300a833cc28109 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 13 Aug 2018 16:23:17 -0400 Subject: formatting for new READMEs --- googlemock/include/gmock/internal/custom/README.md | 12 +++--- googletest/include/gtest/internal/custom/README.md | 44 +++++++++++----------- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/googlemock/include/gmock/internal/custom/README.md b/googlemock/include/gmock/internal/custom/README.md index ef5f9bf..76969a7 100644 --- a/googlemock/include/gmock/internal/custom/README.md +++ b/googlemock/include/gmock/internal/custom/README.md @@ -8,9 +8,9 @@ The following macros can be defined: ### Flag related macros: -* GMOCK_DECLARE_bool_(name) -* GMOCK_DECLARE_int32_(name) -* GMOCK_DECLARE_string_(name) -* GMOCK_DEFINE_bool_(name, default_val, doc) -* GMOCK_DEFINE_int32_(name, default_val, doc) -* GMOCK_DEFINE_string_(name, default_val, doc) +* `GMOCK_DECLARE_bool_(name)` +* `GMOCK_DECLARE_int32_(name)` +* `GMOCK_DECLARE_string_(name)` +* `GMOCK_DEFINE_bool_(name, default_val, doc)` +* `GMOCK_DEFINE_int32_(name, default_val, doc)` +* `GMOCK_DEFINE_string_(name, default_val, doc)` diff --git a/googletest/include/gtest/internal/custom/README.md b/googletest/include/gtest/internal/custom/README.md index e39b7c6..3a2b885 100644 --- a/googletest/include/gtest/internal/custom/README.md +++ b/googletest/include/gtest/internal/custom/README.md @@ -6,9 +6,9 @@ The custom directory is an injection point for custom user configurations. ### The following macros can be defined: -* GTEST_OS_STACK_TRACE_GETTER_ - The name of an implementation of +* `GTEST_OS_STACK_TRACE_GETTER_` - The name of an implementation of OsStackTraceGetterInterface. -* GTEST_CUSTOM_TEMPDIR_FUNCTION_ - An override for testing::TempDir(). See +* `GTEST_CUSTOM_TEMPDIR_FUNCTION_` - An override for testing::TempDir(). See testing::TempDir for semantics and signature. ## Header gtest-port.h @@ -17,38 +17,38 @@ The following macros can be defined: ### Flag related macros: -* GTEST_FLAG(flag_name) -* GTEST_USE_OWN_FLAGFILE_FLAG_ - Define to 0 when the system provides its own - flagfile flag parsing. -* GTEST_DECLARE_bool_(name) -* GTEST_DECLARE_int32_(name) -* GTEST_DECLARE_string_(name) * -* GTEST_DEFINE_bool_(name, default_val, doc) -* GTEST_DEFINE_int32_(name, default_val, doc) -* GTEST_DEFINE_string_(name, default_val, doc) +* `GTEST_FLAG(flag_name)` +* `GTEST_USE_OWN_FLAGFILE_FLAG_` - Define to 0 when the system provides its + own flagfile flag parsing. +* `GTEST_DECLARE_bool_(name)` +* `GTEST_DECLARE_int32_(name)` +* `GTEST_DECLARE_string_(name)` +* `GTEST_DEFINE_bool_(name, default_val, doc)` +* `GTEST_DEFINE_int32_(name, default_val, doc)` +* `GTEST_DEFINE_string_(name, default_val, doc)` ### Logging: -* GTEST_LOG_(severity) -* GTEST_CHECK_(condition) -* Functions LogToStderr() and FlushInfoLog() have to be provided too. +* `GTEST_LOG_(severity)` +* `GTEST_CHECK_(condition)` +* Functions `LogToStderr()` and `FlushInfoLog()` have to be provided too. ### Threading: -* GTEST_HAS_NOTIFICATION_ - Enabled if Notification is already provided. -* GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Enabled if Mutex and ThreadLocal are - already provided. Must also provide GTEST_DECLARE_STATIC_MUTEX_(mutex) and - GTEST_DEFINE_STATIC_MUTEX_(mutex) -* GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) -* GTEST_LOCK_EXCLUDED_(locks) +* `GTEST_HAS_NOTIFICATION_` - Enabled if Notification is already provided. +* `GTEST_HAS_MUTEX_AND_THREAD_LOCAL_` - Enabled if Mutex and ThreadLocal are + already provided. Must also provide `GTEST_DECLARE_STATIC_MUTEX_(mutex)` and + `GTEST_DEFINE_STATIC_MUTEX_(mutex)` +* `GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)` +* `GTEST_LOCK_EXCLUDED_(locks)` ### Underlying library support features -* GTEST_HAS_CXXABI_H_ +* `GTEST_HAS_CXXABI_H_` ### Exporting API symbols: -* GTEST_API_ - Specifier for exported symbols. +* `GTEST_API_` - Specifier for exported symbols. ## Header gtest-printers.h -- cgit v0.12 From c203bee2457e9d098fcca3b136dc8316c4f63bdb Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 13 Aug 2018 22:45:53 -0400 Subject: formatting custom/README.md --- googlemock/include/gmock/internal/custom/README.md | 2 +- googletest/include/gtest/internal/custom/README.md | 20 ++++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/googlemock/include/gmock/internal/custom/README.md b/googlemock/include/gmock/internal/custom/README.md index 76969a7..f6c93f6 100644 --- a/googlemock/include/gmock/internal/custom/README.md +++ b/googlemock/include/gmock/internal/custom/README.md @@ -2,7 +2,7 @@ The custom directory is an injection point for custom user configurations. -## Header gmock-port.h +## Header `gmock-port.h` The following macros can be defined: diff --git a/googletest/include/gtest/internal/custom/README.md b/googletest/include/gtest/internal/custom/README.md index 3a2b885..ff391fb 100644 --- a/googletest/include/gtest/internal/custom/README.md +++ b/googletest/include/gtest/internal/custom/README.md @@ -2,16 +2,16 @@ The custom directory is an injection point for custom user configurations. -## Header gtest.h +## Header `gtest.h` ### The following macros can be defined: * `GTEST_OS_STACK_TRACE_GETTER_` - The name of an implementation of - OsStackTraceGetterInterface. -* `GTEST_CUSTOM_TEMPDIR_FUNCTION_` - An override for testing::TempDir(). See - testing::TempDir for semantics and signature. + `OsStackTraceGetterInterface`. +* `GTEST_CUSTOM_TEMPDIR_FUNCTION_` - An override for `testing::TempDir()`. See + `testing::TempDir` for semantics and signature. -## Header gtest-port.h +## Header `gtest-port.h` The following macros can be defined: @@ -36,9 +36,9 @@ The following macros can be defined: ### Threading: * `GTEST_HAS_NOTIFICATION_` - Enabled if Notification is already provided. -* `GTEST_HAS_MUTEX_AND_THREAD_LOCAL_` - Enabled if Mutex and ThreadLocal are - already provided. Must also provide `GTEST_DECLARE_STATIC_MUTEX_(mutex)` and - `GTEST_DEFINE_STATIC_MUTEX_(mutex)` +* `GTEST_HAS_MUTEX_AND_THREAD_LOCAL_` - Enabled if `Mutex` and `ThreadLocal` + are already provided. Must also provide `GTEST_DECLARE_STATIC_MUTEX_(mutex)` + and `GTEST_DEFINE_STATIC_MUTEX_(mutex)` * `GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)` * `GTEST_LOCK_EXCLUDED_(locks)` @@ -50,7 +50,7 @@ The following macros can be defined: * `GTEST_API_` - Specifier for exported symbols. -## Header gtest-printers.h +## Header `gtest-printers.h` -* See documentation at gtest/gtest-printers.h for details on how to define a +* See documentation at `gtest/gtest-printers.h` for details on how to define a custom printer. -- cgit v0.12 From f225735222b522abcb8286a654e71090403b75a1 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Tue, 14 Aug 2018 11:08:35 -0400 Subject: Code formatting changes, clean up, no functionality changes --- googlemock/include/gmock/gmock-generated-actions.h | 15 +++++---------- googlemock/include/gmock/gmock-generated-actions.h.pump | 3 +-- googletest/src/gtest-death-test.cc | 1 - googletest/test/googletest-printers-test.cc | 2 -- 4 files changed, 6 insertions(+), 15 deletions(-) diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h index 4ce7d35..cd3a102 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h +++ b/googlemock/include/gmock/gmock-generated-actions.h @@ -215,8 +215,7 @@ class InvokeHelper > { get<2>(args), get<3>(args), get<4>(args), get<5>(args)); } - // There is no InvokeCallback() for 6-tuples, as google3 callbacks - // support 5 arguments at most. + // There is no InvokeCallback() for 6-tuples }; template > { get<6>(args)); } - // There is no InvokeCallback() for 7-tuples, as google3 callbacks - // support 5 arguments at most. + // There is no InvokeCallback() for 7-tuples }; template > { get<6>(args), get<7>(args)); } - // There is no InvokeCallback() for 8-tuples, as google3 callbacks - // support 5 arguments at most. + // There is no InvokeCallback() for 8-tuples }; template > { get<6>(args), get<7>(args), get<8>(args)); } - // There is no InvokeCallback() for 9-tuples, as google3 callbacks - // support 5 arguments at most. + // There is no InvokeCallback() for 9-tuples }; template (args), get<7>(args), get<8>(args), get<9>(args)); } - // There is no InvokeCallback() for 10-tuples, as google3 callbacks - // support 5 arguments at most. + // There is no InvokeCallback() for 10-tuples }; // Implements the Invoke(callback) action. diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump index 4ec6679..9db68d9 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/gmock-generated-actions.h.pump @@ -88,8 +88,7 @@ $if i <= max_callback_arity [[ return callback->Run($gets); } ]] $else [[ - // There is no InvokeCallback() for $i-tuples, as google3 callbacks - // support $max_callback_arity arguments at most. + // There is no InvokeCallback() for $i-tuples ]] }; diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 854bc46..4da66c0 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -582,7 +582,6 @@ bool DeathTestImpl::Passed(bool status_ok) { if (status_ok) { # if GTEST_USES_PCRE // PCRE regexes support embedded NULs. - // GTEST_USES_PCRE is defined only in google3 mode const bool matched = RE::PartialMatch(error_message, *regex()); # else const bool matched = RE::PartialMatch(error_message.c_str(), *regex()); diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index 4018863..e4bb0c2 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -919,8 +919,6 @@ TEST(PrintStlContainerTest, MultiSet) { } #if GTEST_HAS_STD_FORWARD_LIST_ -// is available on Linux in the google3 mode, but not on -// Windows or Mac OS X. TEST(PrintStlContainerTest, SinglyLinkedList) { int a[] = { 9, 2, 8 }; -- cgit v0.12 From a3c0dd0f4d58e6c01a1432fdc69a9aff937309a9 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Tue, 14 Aug 2018 14:04:07 -0400 Subject: Comments changes, no functionality changes --- googlemock/include/gmock/gmock-actions.h | 3 +-- googlemock/include/gmock/gmock-cardinalities.h | 3 +-- googlemock/include/gmock/gmock-generated-actions.h | 3 +-- googlemock/include/gmock/gmock-generated-actions.h.pump | 3 +-- googlemock/include/gmock/gmock-generated-function-mockers.h | 3 +-- googlemock/include/gmock/gmock-generated-function-mockers.h.pump | 3 +-- googlemock/include/gmock/gmock-generated-nice-strict.h | 3 +-- googlemock/include/gmock/gmock-generated-nice-strict.h.pump | 3 +-- googlemock/include/gmock/gmock-matchers.h | 3 +-- googlemock/include/gmock/gmock-more-actions.h | 3 +-- googlemock/include/gmock/gmock-more-matchers.h | 3 +-- googlemock/include/gmock/gmock-spec-builders.h | 3 +-- googlemock/include/gmock/gmock.h | 3 +-- googlemock/include/gmock/internal/gmock-generated-internal-utils.h | 3 +-- .../include/gmock/internal/gmock-generated-internal-utils.h.pump | 3 +-- googlemock/include/gmock/internal/gmock-internal-utils.h | 3 +-- googlemock/include/gmock/internal/gmock-port.h | 3 +-- googlemock/src/gmock-all.cc | 3 +-- googlemock/src/gmock-cardinalities.cc | 3 +-- googlemock/src/gmock-internal-utils.cc | 3 +-- googlemock/src/gmock-matchers.cc | 3 +-- googlemock/src/gmock-spec-builders.cc | 3 +-- googlemock/src/gmock.cc | 3 +-- googlemock/src/gmock_main.cc | 3 +-- googlemock/test/gmock-actions_test.cc | 3 +-- googlemock/test/gmock-cardinalities_test.cc | 3 +-- googlemock/test/gmock-generated-actions_test.cc | 3 +-- googlemock/test/gmock-generated-function-mockers_test.cc | 3 +-- googlemock/test/gmock-generated-internal-utils_test.cc | 3 +-- googlemock/test/gmock-internal-utils_test.cc | 3 +-- googlemock/test/gmock-matchers_test.cc | 3 +-- googlemock/test/gmock-more-actions_test.cc | 3 +-- googlemock/test/gmock-nice-strict_test.cc | 3 +-- googlemock/test/gmock-port_test.cc | 3 +-- googlemock/test/gmock-spec-builders_test.cc | 3 +-- googlemock/test/gmock_all_test.cc | 3 +-- googlemock/test/gmock_ex_test.cc | 3 +-- googlemock/test/gmock_leak_test_.cc | 3 +-- googlemock/test/gmock_link2_test.cc | 3 +-- googlemock/test/gmock_link_test.cc | 3 +-- googlemock/test/gmock_link_test.h | 3 +-- googlemock/test/gmock_output_test_.cc | 3 +-- googlemock/test/gmock_stress_test.cc | 3 +-- googlemock/test/gmock_test.cc | 3 +-- googletest/include/gtest/gtest-death-test.h | 3 +-- googletest/include/gtest/gtest-message.h | 3 +-- googletest/include/gtest/gtest-param-test.h | 2 -- googletest/include/gtest/gtest-param-test.h.pump | 2 -- googletest/include/gtest/gtest-printers.h | 3 +-- googletest/include/gtest/gtest-spi.h | 3 +-- googletest/include/gtest/gtest-test-part.h | 3 --- googletest/include/gtest/gtest-typed-test.h | 3 +-- googletest/include/gtest/gtest.h | 3 +-- googletest/include/gtest/gtest_prod.h | 3 +-- googletest/include/gtest/internal/gtest-death-test-internal.h | 1 - googletest/include/gtest/internal/gtest-filepath.h | 1 - googletest/include/gtest/internal/gtest-internal.h | 1 - googletest/include/gtest/internal/gtest-linked_ptr.h | 2 -- googletest/include/gtest/internal/gtest-param-util-generated.h | 3 +-- googletest/include/gtest/internal/gtest-param-util-generated.h.pump | 3 +-- googletest/include/gtest/internal/gtest-param-util.h | 3 +-- googletest/include/gtest/internal/gtest-port.h | 2 -- googletest/include/gtest/internal/gtest-string.h | 1 - googletest/include/gtest/internal/gtest-tuple.h | 3 +-- googletest/include/gtest/internal/gtest-tuple.h.pump | 3 +-- googletest/include/gtest/internal/gtest-type-util.h | 3 +-- googletest/include/gtest/internal/gtest-type-util.h.pump | 3 +-- googletest/samples/prime_tables.h | 5 ++--- googletest/samples/sample1.cc | 2 -- googletest/samples/sample1.h | 2 -- googletest/samples/sample10_unittest.cc | 3 +-- googletest/samples/sample1_unittest.cc | 3 --- googletest/samples/sample2.cc | 2 -- googletest/samples/sample2.h | 2 -- googletest/samples/sample2_unittest.cc | 3 --- googletest/samples/sample3-inl.h | 2 -- googletest/samples/sample3_unittest.cc | 3 --- googletest/samples/sample4.cc | 2 -- googletest/samples/sample4.h | 3 --- googletest/samples/sample4_unittest.cc | 3 +-- googletest/samples/sample5_unittest.cc | 3 +-- googletest/samples/sample6_unittest.cc | 3 +-- googletest/samples/sample7_unittest.cc | 3 +-- googletest/samples/sample8_unittest.cc | 3 +-- googletest/samples/sample9_unittest.cc | 3 +-- googletest/src/gtest-all.cc | 3 +-- googletest/src/gtest-death-test.cc | 3 +-- googletest/src/gtest-internal-inl.h | 5 +---- googletest/src/gtest-port.cc | 3 +-- googletest/src/gtest-printers.cc | 3 +-- googletest/src/gtest-test-part.cc | 3 +-- googletest/src/gtest-typed-test.cc | 3 +-- googletest/src/gtest.cc | 3 +-- googletest/src/gtest_main.cc | 1 - googletest/test/googletest-break-on-failure-unittest_.cc | 3 +-- googletest/test/googletest-catch-exceptions-test_.cc | 3 +-- googletest/test/googletest-color-test_.cc | 3 +-- googletest/test/googletest-death-test-test.cc | 3 +-- googletest/test/googletest-death-test_ex_test.cc | 3 +-- googletest/test/googletest-env-var-test_.cc | 3 +-- googletest/test/googletest-filepath-test.cc | 1 - googletest/test/googletest-filter-unittest_.cc | 3 +-- googletest/test/googletest-linked-ptr-test.cc | 3 --- googletest/test/googletest-list-tests-unittest_.cc | 3 +-- googletest/test/googletest-listener-test.cc | 3 +-- googletest/test/googletest-message-test.cc | 3 +-- googletest/test/googletest-options-test.cc | 1 - googletest/test/googletest-output-test_.cc | 2 -- googletest/test/googletest-param-test-invalid-name1-test_.cc | 3 +-- googletest/test/googletest-param-test-invalid-name2-test_.cc | 3 +-- googletest/test/googletest-param-test-test.cc | 3 +-- googletest/test/googletest-param-test-test.h | 2 -- googletest/test/googletest-param-test2-test.cc | 3 +-- googletest/test/googletest-port-test.cc | 2 -- googletest/test/googletest-printers-test.cc | 3 +-- googletest/test/googletest-shuffle-test_.cc | 3 +-- googletest/test/googletest-test-part-test.cc | 3 --- googletest/test/googletest-test2_test.cc | 3 +-- googletest/test/googletest-throw-on-failure-test_.cc | 3 +-- googletest/test/googletest-tuple-test.cc | 3 +-- googletest/test/googletest-uninitialized-test_.cc | 3 +-- googletest/test/gtest-typed-test2_test.cc | 3 +-- googletest/test/gtest-typed-test_test.cc | 3 +-- googletest/test/gtest-typed-test_test.h | 3 +-- googletest/test/gtest-unittest-api_test.cc | 3 +-- googletest/test/gtest_all_test.cc | 3 +-- googletest/test/gtest_assert_by_exception_test.cc | 3 +-- googletest/test/gtest_environment_test.cc | 3 +-- googletest/test/gtest_help_test_.cc | 3 +-- googletest/test/gtest_main_unittest.cc | 3 +-- googletest/test/gtest_no_test_unittest.cc | 2 -- googletest/test/gtest_premature_exit_test.cc | 3 +-- googletest/test/gtest_prod_test.cc | 3 +-- googletest/test/gtest_repeat_test.cc | 3 +-- googletest/test/gtest_sole_header_test.cc | 3 +-- googletest/test/gtest_stress_test.cc | 3 +-- googletest/test/gtest_test_macro_stack_footprint_test.cc | 3 +-- googletest/test/gtest_testbridge_test_.cc | 3 +-- googletest/test/gtest_throw_on_failure_ex_test.cc | 3 +-- googletest/test/gtest_unittest.cc | 3 +-- googletest/test/gtest_xml_outfile1_test_.cc | 1 - googletest/test/gtest_xml_outfile2_test_.cc | 1 - googletest/test/production.cc | 3 +-- googletest/test/production.h | 3 +-- 144 files changed, 115 insertions(+), 289 deletions(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index 42648ad..b82313d 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/gmock-cardinalities.h b/googlemock/include/gmock/gmock-cardinalities.h index 2ce16af..bf3ae55 100644 --- a/googlemock/include/gmock/gmock-cardinalities.h +++ b/googlemock/include/gmock/gmock-cardinalities.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h index cd3a102..260036d 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h +++ b/googlemock/include/gmock/gmock-generated-actions.h @@ -30,8 +30,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump index 9db68d9..f1ee4a6 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/gmock-generated-actions.h.pump @@ -32,8 +32,7 @@ $$}} This meta comment fixes auto-indentation in editors. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h b/googlemock/include/gmock/gmock-generated-function-mockers.h index 0474c89..5792d3d 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h @@ -30,8 +30,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump index f6e1781..82f9512 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump @@ -31,8 +31,7 @@ $var n = 10 $$ The maximum arity we support. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/gmock-generated-nice-strict.h b/googlemock/include/gmock/gmock-generated-nice-strict.h index 96d6f39..91ba1d9 100644 --- a/googlemock/include/gmock/gmock-generated-nice-strict.h +++ b/googlemock/include/gmock/gmock-generated-nice-strict.h @@ -30,8 +30,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Implements class templates NiceMock, NaggyMock, and StrictMock. // diff --git a/googlemock/include/gmock/gmock-generated-nice-strict.h.pump b/googlemock/include/gmock/gmock-generated-nice-strict.h.pump index 7c2bf36..ed49f4a 100644 --- a/googlemock/include/gmock/gmock-generated-nice-strict.h.pump +++ b/googlemock/include/gmock/gmock-generated-nice-strict.h.pump @@ -31,8 +31,7 @@ $var n = 10 $$ The maximum arity we support. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Implements class templates NiceMock, NaggyMock, and StrictMock. // diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index adf4999..490f3a4 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/gmock-more-actions.h b/googlemock/include/gmock/gmock-more-actions.h index 1106818..4d9a28e 100644 --- a/googlemock/include/gmock/gmock-more-actions.h +++ b/googlemock/include/gmock/gmock-more-actions.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/gmock-more-matchers.h b/googlemock/include/gmock/gmock-more-matchers.h index 6c6b3e3..e5460e7 100644 --- a/googlemock/include/gmock/gmock-more-matchers.h +++ b/googlemock/include/gmock/gmock-more-matchers.h @@ -26,8 +26,7 @@ // 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: marcus.boerger@google.com (Marcus Boerger) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index 9670b59..f49d01f 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/gmock.h b/googlemock/include/gmock/gmock.h index 6330294..dd96226 100644 --- a/googlemock/include/gmock/gmock.h +++ b/googlemock/include/gmock/gmock.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h index c9bfbc8..eaa56be 100644 --- a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h @@ -30,8 +30,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump index f13151b..c103279 100644 --- a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump +++ b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump @@ -31,8 +31,7 @@ $var n = 10 $$ The maximum arity we support. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index e0846d9..b020f89 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/include/gmock/internal/gmock-port.h b/googlemock/include/gmock/internal/gmock-port.h index 79f4366..fda27db 100644 --- a/googlemock/include/gmock/internal/gmock-port.h +++ b/googlemock/include/gmock/internal/gmock-port.h @@ -26,8 +26,7 @@ // 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: vadimb@google.com (Vadim Berman) + // // Low-level types and utilities for porting Google Mock to various // platforms. All macros ending with _ and symbols defined in an diff --git a/googlemock/src/gmock-all.cc b/googlemock/src/gmock-all.cc index 7aebce7..e43c9b7 100644 --- a/googlemock/src/gmock-all.cc +++ b/googlemock/src/gmock-all.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Google C++ Mocking Framework (Google Mock) // diff --git a/googlemock/src/gmock-cardinalities.cc b/googlemock/src/gmock-cardinalities.cc index 335b966..0549f72 100644 --- a/googlemock/src/gmock-cardinalities.cc +++ b/googlemock/src/gmock-cardinalities.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/src/gmock-internal-utils.cc b/googlemock/src/gmock-internal-utils.cc index 77caf2b..e3a6748 100644 --- a/googlemock/src/gmock-internal-utils.cc +++ b/googlemock/src/gmock-internal-utils.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/src/gmock-matchers.cc b/googlemock/src/gmock-matchers.cc index 194d992..f8ddff1 100644 --- a/googlemock/src/gmock-matchers.cc +++ b/googlemock/src/gmock-matchers.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc index 22d002f..83cc9cc 100644 --- a/googlemock/src/gmock-spec-builders.cc +++ b/googlemock/src/gmock-spec-builders.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/src/gmock.cc b/googlemock/src/gmock.cc index 2308168..1cebede 100644 --- a/googlemock/src/gmock.cc +++ b/googlemock/src/gmock.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index 32ab534..a3a271e 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include #include "gmock/gmock.h" diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index e8bdbee..e216fe2 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock-cardinalities_test.cc b/googlemock/test/gmock-cardinalities_test.cc index 04c792b..132591b 100644 --- a/googlemock/test/gmock-cardinalities_test.cc +++ b/googlemock/test/gmock-cardinalities_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock-generated-actions_test.cc b/googlemock/test/gmock-generated-actions_test.cc index 40bbe6d..a460280 100644 --- a/googlemock/test/gmock-generated-actions_test.cc +++ b/googlemock/test/gmock-generated-actions_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock-generated-function-mockers_test.cc b/googlemock/test/gmock-generated-function-mockers_test.cc index 0ff3755..f16833b 100644 --- a/googlemock/test/gmock-generated-function-mockers_test.cc +++ b/googlemock/test/gmock-generated-function-mockers_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock-generated-internal-utils_test.cc b/googlemock/test/gmock-generated-internal-utils_test.cc index 2e5abe5..ae0280f 100644 --- a/googlemock/test/gmock-generated-internal-utils_test.cc +++ b/googlemock/test/gmock-generated-internal-utils_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock-internal-utils_test.cc b/googlemock/test/gmock-internal-utils_test.cc index f8633df..5f53077 100644 --- a/googlemock/test/gmock-internal-utils_test.cc +++ b/googlemock/test/gmock-internal-utils_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index 9f1a547..d08f08f 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock-more-actions_test.cc b/googlemock/test/gmock-more-actions_test.cc index b13518a..08a2df0 100644 --- a/googlemock/test/gmock-more-actions_test.cc +++ b/googlemock/test/gmock-more-actions_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock-nice-strict_test.cc b/googlemock/test/gmock-nice-strict_test.cc index c419494..dce6642 100644 --- a/googlemock/test/gmock-nice-strict_test.cc +++ b/googlemock/test/gmock-nice-strict_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include "gmock/gmock-generated-nice-strict.h" diff --git a/googlemock/test/gmock-port_test.cc b/googlemock/test/gmock-port_test.cc index d6a8d44..a2c2be2 100644 --- a/googlemock/test/gmock-port_test.cc +++ b/googlemock/test/gmock-port_test.cc @@ -26,8 +26,7 @@ // 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) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock-spec-builders_test.cc b/googlemock/test/gmock-spec-builders_test.cc index 715aac8..78fbc3f 100644 --- a/googlemock/test/gmock-spec-builders_test.cc +++ b/googlemock/test/gmock-spec-builders_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock_all_test.cc b/googlemock/test/gmock_all_test.cc index 56d6c49..e1774fb 100644 --- a/googlemock/test/gmock_all_test.cc +++ b/googlemock/test/gmock_all_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests for Google C++ Mocking Framework (Google Mock) // diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc index b03de82..72eb43f 100644 --- a/googlemock/test/gmock_ex_test.cc +++ b/googlemock/test/gmock_ex_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests Google Mock's functionality that depends on exceptions. diff --git a/googlemock/test/gmock_leak_test_.cc b/googlemock/test/gmock_leak_test_.cc index 1d27d22..2e095ab 100644 --- a/googlemock/test/gmock_leak_test_.cc +++ b/googlemock/test/gmock_leak_test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock_link2_test.cc b/googlemock/test/gmock_link2_test.cc index 2b48395..d27ce17 100644 --- a/googlemock/test/gmock_link2_test.cc +++ b/googlemock/test/gmock_link2_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock_link_test.cc b/googlemock/test/gmock_link_test.cc index ef041be..e7c54cc 100644 --- a/googlemock/test/gmock_link_test.cc +++ b/googlemock/test/gmock_link_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock_link_test.h b/googlemock/test/gmock_link_test.h index 06a1cf8..d26670e 100644 --- a/googlemock/test/gmock_link_test.h +++ b/googlemock/test/gmock_link_test.h @@ -26,8 +26,7 @@ // 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) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googlemock/test/gmock_output_test_.cc b/googlemock/test/gmock_output_test_.cc index 1b59eb3..3955c73 100644 --- a/googlemock/test/gmock_output_test_.cc +++ b/googlemock/test/gmock_output_test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests Google Mock's output in various scenarios. This ensures that // Google Mock's messages are readable and useful. diff --git a/googlemock/test/gmock_stress_test.cc b/googlemock/test/gmock_stress_test.cc index e4e61f0..0d99bed 100644 --- a/googlemock/test/gmock_stress_test.cc +++ b/googlemock/test/gmock_stress_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests that Google Mock constructs can be used in a large number of // threads concurrently. diff --git a/googlemock/test/gmock_test.cc b/googlemock/test/gmock_test.cc index 7007567..341a17d 100644 --- a/googlemock/test/gmock_test.cc +++ b/googlemock/test/gmock_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Mock - a framework for writing C++ mock classes. // diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h index 59795e3..06fe42e 100644 --- a/googletest/include/gtest/gtest-death-test.h +++ b/googletest/include/gtest/gtest-death-test.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // The Google C++ Testing and Mocking Framework (Google Test) // diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h index 3e3870c..107a55c 100644 --- a/googletest/include/gtest/gtest-message.h +++ b/googletest/include/gtest/gtest-message.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // The Google C++ Testing and Mocking Framework (Google Test) // diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index 3ea3338..1e22f68 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -31,8 +31,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// Authors: vladl@google.com (Vlad Losev) -// // Macros and functions for implementing parameterized tests // in Google C++ Testing and Mocking Framework (Google Test) // diff --git a/googletest/include/gtest/gtest-param-test.h.pump b/googletest/include/gtest/gtest-param-test.h.pump index 4dac9f2..274f2b3 100644 --- a/googletest/include/gtest/gtest-param-test.h.pump +++ b/googletest/include/gtest/gtest-param-test.h.pump @@ -30,8 +30,6 @@ $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// Authors: vladl@google.com (Vlad Losev) -// // Macros and functions for implementing parameterized tests // in Google C++ Testing and Mocking Framework (Google Test) // diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index 57eb5ae..f4accac 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Test - The Google C++ Testing and Mocking Framework // diff --git a/googletest/include/gtest/gtest-spi.h b/googletest/include/gtest/gtest-spi.h index c21b029..26b4aa5 100644 --- a/googletest/include/gtest/gtest-spi.h +++ b/googletest/include/gtest/gtest-spi.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Utilities for testing Google Test itself and code that uses Google Test // (e.g. frameworks built on top of Google Test). diff --git a/googletest/include/gtest/gtest-test-part.h b/googletest/include/gtest/gtest-test-part.h index 301a012..66c7db6 100644 --- a/googletest/include/gtest/gtest-test-part.h +++ b/googletest/include/gtest/gtest-test-part.h @@ -27,9 +27,6 @@ // (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: mheule@google.com (Markus Heule) -// - // GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h index 00925af..61d8907 100644 --- a/googletest/include/gtest/gtest-typed-test.h +++ b/googletest/include/gtest/gtest-typed-test.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // GOOGLETEST_CM0001 DO NOT DELETE diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index a6c674b..f374c59 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // The Google C++ Testing and Mocking Framework (Google Test) // diff --git a/googletest/include/gtest/gtest_prod.h b/googletest/include/gtest/gtest_prod.h index 71377f8..e651671 100644 --- a/googletest/include/gtest/gtest_prod.h +++ b/googletest/include/gtest/gtest_prod.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Google C++ Testing and Mocking Framework definitions useful in production code. // GOOGLETEST_CM0003 DO NOT DELETE diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h index 719aee6..55e3029 100644 --- a/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// // The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines internal utilities needed for implementing diff --git a/googletest/include/gtest/internal/gtest-filepath.h b/googletest/include/gtest/internal/gtest-filepath.h index e18fe45..c2601a3 100644 --- a/googletest/include/gtest/internal/gtest-filepath.h +++ b/googletest/include/gtest/internal/gtest-filepath.h @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// // Google Test filepath utilities // // This header file declares classes and functions used internally by diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index 45192e2..aa36693 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// // The Google C++ Testing and Mocking Framework (Google Test) // // This header file declares functions and macros used internally by diff --git a/googletest/include/gtest/internal/gtest-linked_ptr.h b/googletest/include/gtest/internal/gtest-linked_ptr.h index 8e1caa0..fa2c3b3 100644 --- a/googletest/include/gtest/internal/gtest-linked_ptr.h +++ b/googletest/include/gtest/internal/gtest-linked_ptr.h @@ -27,8 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// Authors: Dan Egnor (egnor@google.com) -// // A "smart" pointer type with reference tracking. Every pointer to a // particular object is kept on a circular linked list. When the last pointer // to an object is destroyed or reassigned, the object is deleted. diff --git a/googletest/include/gtest/internal/gtest-param-util-generated.h b/googletest/include/gtest/internal/gtest-param-util-generated.h index ef22e89..f4df599 100644 --- a/googletest/include/gtest/internal/gtest-param-util-generated.h +++ b/googletest/include/gtest/internal/gtest-param-util-generated.h @@ -30,8 +30,7 @@ // 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) + // Type and function utilities for implementing parameterized tests. // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! diff --git a/googletest/include/gtest/internal/gtest-param-util-generated.h.pump b/googletest/include/gtest/internal/gtest-param-util-generated.h.pump index 856caba..ae8c57b 100644 --- a/googletest/include/gtest/internal/gtest-param-util-generated.h.pump +++ b/googletest/include/gtest/internal/gtest-param-util-generated.h.pump @@ -29,8 +29,7 @@ $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. // 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) + // Type and function utilities for implementing parameterized tests. // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h index a69d5de..d64f620 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -26,8 +26,7 @@ // 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) + // Type and function utilities for implementing parameterized tests. diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 9afa1ff..5d96a05 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -27,8 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// Authors: wan@google.com (Zhanyong Wan) -// // Low-level types and utilities for porting Google Test to various // platforms. All macros ending with _ and symbols defined in an // internal namespace are subject to change without notice. Code diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h index 1d2436c..4c9b626 100644 --- a/googletest/include/gtest/internal/gtest-string.h +++ b/googletest/include/gtest/internal/gtest-string.h @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// // The Google C++ Testing and Mocking Framework (Google Test) // // This header file declares the String class and functions used internally by diff --git a/googletest/include/gtest/internal/gtest-tuple.h b/googletest/include/gtest/internal/gtest-tuple.h index e64cede..89748cc 100644 --- a/googletest/include/gtest/internal/gtest-tuple.h +++ b/googletest/include/gtest/internal/gtest-tuple.h @@ -30,8 +30,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Implements a subset of TR1 tuple needed by Google Test and Google Mock. diff --git a/googletest/include/gtest/internal/gtest-tuple.h.pump b/googletest/include/gtest/internal/gtest-tuple.h.pump index 2736360..a08bf70 100644 --- a/googletest/include/gtest/internal/gtest-tuple.h.pump +++ b/googletest/include/gtest/internal/gtest-tuple.h.pump @@ -29,8 +29,7 @@ $$ This meta comment fixes auto-indentation in Emacs. }} // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Implements a subset of TR1 tuple needed by Google Test and Google Mock. diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h index 2681dbb..28e4112 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h +++ b/googletest/include/gtest/internal/gtest-type-util.h @@ -30,8 +30,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Type utilities needed for implementing typed and type-parameterized // tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! diff --git a/googletest/include/gtest/internal/gtest-type-util.h.pump b/googletest/include/gtest/internal/gtest-type-util.h.pump index 8897795..0001a5d 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h.pump +++ b/googletest/include/gtest/internal/gtest-type-util.h.pump @@ -28,8 +28,7 @@ $var n = 50 $$ Maximum length of type lists we want to support. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Type utilities needed for implementing typed and type-parameterized // tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! diff --git a/googletest/samples/prime_tables.h b/googletest/samples/prime_tables.h index 55a3b44..523c50b 100644 --- a/googletest/samples/prime_tables.h +++ b/googletest/samples/prime_tables.h @@ -26,9 +26,8 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) -// Author: vladl@google.com (Vlad Losev) + + // This provides interface PrimeTable that determines whether a number is a // prime and determines a next prime number. This interface is used diff --git a/googletest/samples/sample1.cc b/googletest/samples/sample1.cc index 7c08b28..13cec1d 100644 --- a/googletest/samples/sample1.cc +++ b/googletest/samples/sample1.cc @@ -28,8 +28,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. -// -// Author: wan@google.com (Zhanyong Wan) #include "sample1.h" diff --git a/googletest/samples/sample1.h b/googletest/samples/sample1.h index 3dfeb98..2c3e9f0 100644 --- a/googletest/samples/sample1.h +++ b/googletest/samples/sample1.h @@ -28,8 +28,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. -// -// Author: wan@google.com (Zhanyong Wan) #ifndef GTEST_SAMPLES_SAMPLE1_H_ #define GTEST_SAMPLES_SAMPLE1_H_ diff --git a/googletest/samples/sample10_unittest.cc b/googletest/samples/sample10_unittest.cc index 10aa762..7ce9550 100644 --- a/googletest/samples/sample10_unittest.cc +++ b/googletest/samples/sample10_unittest.cc @@ -25,8 +25,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: vladl@google.com (Vlad Losev) + // This sample shows how to use Google Test listener API to implement // a primitive leak checker. diff --git a/googletest/samples/sample1_unittest.cc b/googletest/samples/sample1_unittest.cc index 8376bb4..cb08b61 100644 --- a/googletest/samples/sample1_unittest.cc +++ b/googletest/samples/sample1_unittest.cc @@ -28,9 +28,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. -// -// Author: wan@google.com (Zhanyong Wan) - // This sample shows how to write a simple unit test for a function, // using Google C++ testing framework. diff --git a/googletest/samples/sample2.cc b/googletest/samples/sample2.cc index 5f763b9..f3b722f 100644 --- a/googletest/samples/sample2.cc +++ b/googletest/samples/sample2.cc @@ -28,8 +28,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. -// -// Author: wan@google.com (Zhanyong Wan) #include "sample2.h" diff --git a/googletest/samples/sample2.h b/googletest/samples/sample2.h index cb485c7..58f360f 100644 --- a/googletest/samples/sample2.h +++ b/googletest/samples/sample2.h @@ -28,8 +28,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. -// -// Author: wan@google.com (Zhanyong Wan) #ifndef GTEST_SAMPLES_SAMPLE2_H_ #define GTEST_SAMPLES_SAMPLE2_H_ diff --git a/googletest/samples/sample2_unittest.cc b/googletest/samples/sample2_unittest.cc index df522da..0848826 100644 --- a/googletest/samples/sample2_unittest.cc +++ b/googletest/samples/sample2_unittest.cc @@ -28,9 +28,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. -// -// Author: wan@google.com (Zhanyong Wan) - // This sample shows how to write a more complex unit test for a class // that has multiple member functions. diff --git a/googletest/samples/sample3-inl.h b/googletest/samples/sample3-inl.h index 7e3084d..1a29ce9 100644 --- a/googletest/samples/sample3-inl.h +++ b/googletest/samples/sample3-inl.h @@ -28,8 +28,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. -// -// Author: wan@google.com (Zhanyong Wan) #ifndef GTEST_SAMPLES_SAMPLE3_INL_H_ #define GTEST_SAMPLES_SAMPLE3_INL_H_ diff --git a/googletest/samples/sample3_unittest.cc b/googletest/samples/sample3_unittest.cc index 7f51fd8..e093c25 100644 --- a/googletest/samples/sample3_unittest.cc +++ b/googletest/samples/sample3_unittest.cc @@ -28,9 +28,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. -// -// Author: wan@google.com (Zhanyong Wan) - // In this example, we use a more advanced feature of Google Test called // test fixture. diff --git a/googletest/samples/sample4.cc b/googletest/samples/sample4.cc index ae44bda..2f7c87a 100644 --- a/googletest/samples/sample4.cc +++ b/googletest/samples/sample4.cc @@ -28,8 +28,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. -// -// Author: wan@google.com (Zhanyong Wan) #include diff --git a/googletest/samples/sample4.h b/googletest/samples/sample4.h index cd60f0d..fda5f33 100644 --- a/googletest/samples/sample4.h +++ b/googletest/samples/sample4.h @@ -28,9 +28,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. -// -// Author: wan@google.com (Zhanyong Wan) - #ifndef GTEST_SAMPLES_SAMPLE4_H_ #define GTEST_SAMPLES_SAMPLE4_H_ diff --git a/googletest/samples/sample4_unittest.cc b/googletest/samples/sample4_unittest.cc index 7bf9ea3..079a70d 100644 --- a/googletest/samples/sample4_unittest.cc +++ b/googletest/samples/sample4_unittest.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include "sample4.h" #include "gtest/gtest.h" diff --git a/googletest/samples/sample5_unittest.cc b/googletest/samples/sample5_unittest.cc index 401a58a..d8a8788 100644 --- a/googletest/samples/sample5_unittest.cc +++ b/googletest/samples/sample5_unittest.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // This sample teaches how to reuse a test fixture in multiple test // cases by deriving sub-fixtures from it. diff --git a/googletest/samples/sample6_unittest.cc b/googletest/samples/sample6_unittest.cc index 1faf0c3..ddf2f1c 100644 --- a/googletest/samples/sample6_unittest.cc +++ b/googletest/samples/sample6_unittest.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // This sample shows how to test common properties of multiple // implementations of the same interface (aka interface tests). diff --git a/googletest/samples/sample7_unittest.cc b/googletest/samples/sample7_unittest.cc index efa9728..c1ae8bd 100644 --- a/googletest/samples/sample7_unittest.cc +++ b/googletest/samples/sample7_unittest.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: vladl@google.com (Vlad Losev) + // This sample shows how to test common properties of multiple // implementations of an interface (aka interface tests) using diff --git a/googletest/samples/sample8_unittest.cc b/googletest/samples/sample8_unittest.cc index b0ff2d1..ce75cf0 100644 --- a/googletest/samples/sample8_unittest.cc +++ b/googletest/samples/sample8_unittest.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: vladl@google.com (Vlad Losev) + // This sample shows how to test code relying on some global flag variables. // Combine() helps with generating all possible combinations of such flags, diff --git a/googletest/samples/sample9_unittest.cc b/googletest/samples/sample9_unittest.cc index 75584bb..53f9af5 100644 --- a/googletest/samples/sample9_unittest.cc +++ b/googletest/samples/sample9_unittest.cc @@ -25,8 +25,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: vladl@google.com (Vlad Losev) + // This sample shows how to use Google Test listener API to implement // an alternative console output and how to use the UnitTest reflection API diff --git a/googletest/src/gtest-all.cc b/googletest/src/gtest-all.cc index 5872a2e..b217a18 100644 --- a/googletest/src/gtest-all.cc +++ b/googletest/src/gtest-all.cc @@ -26,8 +26,7 @@ // 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: mheule@google.com (Markus Heule) + // // Google C++ Testing and Mocking Framework (Google Test) // diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 4da66c0..97dbffc 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) + // // This file implements death tests. diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index c5a4265..f7ed9a1 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -27,10 +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. -// Utility functions and classes used by the Google C++ testing framework. -// -// Author: wan@google.com (Zhanyong Wan) -// +// Utility functions and classes used by the Google C++ testing framework.// // This file contains purely Google Test's internal implementation. Please // DO NOT #INCLUDE IT IN A USER PROGRAM. diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index 71942e5..0b49193 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include "gtest/internal/gtest-port.h" diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc index eeba17f..d68d929 100644 --- a/googletest/src/gtest-printers.cc +++ b/googletest/src/gtest-printers.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Test - The Google C++ Testing and Mocking Framework // diff --git a/googletest/src/gtest-test-part.cc b/googletest/src/gtest-test-part.cc index 4c5f2e3..c88860d 100644 --- a/googletest/src/gtest-test-part.cc +++ b/googletest/src/gtest-test-part.cc @@ -26,8 +26,7 @@ // 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: mheule@google.com (Markus Heule) + // // The Google C++ Testing and Mocking Framework (Google Test) diff --git a/googletest/src/gtest-typed-test.cc b/googletest/src/gtest-typed-test.cc index b358243..1dc2ad3 100644 --- a/googletest/src/gtest-typed-test.cc +++ b/googletest/src/gtest-typed-test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include "gtest/gtest-typed-test.h" diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 691d644..37e5b1f 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // The Google C++ Testing and Mocking Framework (Google Test) diff --git a/googletest/src/gtest_main.cc b/googletest/src/gtest_main.cc index f039d00..2113f62 100644 --- a/googletest/src/gtest_main.cc +++ b/googletest/src/gtest_main.cc @@ -26,7 +26,6 @@ // 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. -// #include #include "gtest/gtest.h" diff --git a/googletest/test/googletest-break-on-failure-unittest_.cc b/googletest/test/googletest-break-on-failure-unittest_.cc index 1231ec2..f84957a 100644 --- a/googletest/test/googletest-break-on-failure-unittest_.cc +++ b/googletest/test/googletest-break-on-failure-unittest_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Unit test for Google Test's break-on-failure mode. // diff --git a/googletest/test/googletest-catch-exceptions-test_.cc b/googletest/test/googletest-catch-exceptions-test_.cc index af2676b..09dae70 100644 --- a/googletest/test/googletest-catch-exceptions-test_.cc +++ b/googletest/test/googletest-catch-exceptions-test_.cc @@ -26,8 +26,7 @@ // 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 diff --git a/googletest/test/googletest-color-test_.cc b/googletest/test/googletest-color-test_.cc index f9a21e2..220a3a0 100644 --- a/googletest/test/googletest-color-test_.cc +++ b/googletest/test/googletest-color-test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // A helper program for testing how Google Test determines whether to use // colors in the output. It prints "YES" and returns 1 if Google Test diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc index 9d8f13c..0699029 100644 --- a/googletest/test/googletest-death-test-test.cc +++ b/googletest/test/googletest-death-test-test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests for death tests. diff --git a/googletest/test/googletest-death-test_ex_test.cc b/googletest/test/googletest-death-test_ex_test.cc index 3391074..b8b9470 100644 --- a/googletest/test/googletest-death-test_ex_test.cc +++ b/googletest/test/googletest-death-test_ex_test.cc @@ -26,8 +26,7 @@ // 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 that verify interaction of exceptions and death tests. diff --git a/googletest/test/googletest-env-var-test_.cc b/googletest/test/googletest-env-var-test_.cc index 4fba7a6..fd2aa82 100644 --- a/googletest/test/googletest-env-var-test_.cc +++ b/googletest/test/googletest-env-var-test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // A helper program for testing that Google Test parses the environment // variables correctly. diff --git a/googletest/test/googletest-filepath-test.cc b/googletest/test/googletest-filepath-test.cc index 29cea3d..e832666 100644 --- a/googletest/test/googletest-filepath-test.cc +++ b/googletest/test/googletest-filepath-test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// // Google Test filepath utilities // // This file tests classes and functions used internally by diff --git a/googletest/test/googletest-filter-unittest_.cc b/googletest/test/googletest-filter-unittest_.cc index e74a7a3..d335b60 100644 --- a/googletest/test/googletest-filter-unittest_.cc +++ b/googletest/test/googletest-filter-unittest_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Unit test for Google Test test filters. // diff --git a/googletest/test/googletest-linked-ptr-test.cc b/googletest/test/googletest-linked-ptr-test.cc index d80ac1e..fa00f34 100644 --- a/googletest/test/googletest-linked-ptr-test.cc +++ b/googletest/test/googletest-linked-ptr-test.cc @@ -26,9 +26,6 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Authors: Dan Egnor (egnor@google.com) -// Ported to Windows: Vadim Berman (vadimb@google.com) #include diff --git a/googletest/test/googletest-list-tests-unittest_.cc b/googletest/test/googletest-list-tests-unittest_.cc index 907c176..f473c7d 100644 --- a/googletest/test/googletest-list-tests-unittest_.cc +++ b/googletest/test/googletest-list-tests-unittest_.cc @@ -26,8 +26,7 @@ // 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: phanna@google.com (Patrick Hanna) + // Unit test for Google Test's --gtest_list_tests flag. // diff --git a/googletest/test/googletest-listener-test.cc b/googletest/test/googletest-listener-test.cc index b01417a..8355597 100644 --- a/googletest/test/googletest-listener-test.cc +++ b/googletest/test/googletest-listener-test.cc @@ -25,8 +25,7 @@ // 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) + // // The Google C++ Testing and Mocking Framework (Google Test) // diff --git a/googletest/test/googletest-message-test.cc b/googletest/test/googletest-message-test.cc index 175238e..c644585 100644 --- a/googletest/test/googletest-message-test.cc +++ b/googletest/test/googletest-message-test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests for the Message class. diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc index e4c0d04..e426ce2 100644 --- a/googletest/test/googletest-options-test.cc +++ b/googletest/test/googletest-options-test.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// // Google Test UnitTestOptions tests // // This file tests classes and functions used internally by diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index 29fc993..3860cf4 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -32,8 +32,6 @@ // googletest-output-test.py to ensure that Google Test generates the // desired messages. Therefore, most tests in this file are MEANT TO // FAIL. -// -// Author: wan@google.com (Zhanyong Wan) #include "gtest/gtest-spi.h" #include "gtest/gtest.h" diff --git a/googletest/test/googletest-param-test-invalid-name1-test_.cc b/googletest/test/googletest-param-test-invalid-name1-test_.cc index 68dd470..5a95155 100644 --- a/googletest/test/googletest-param-test-invalid-name1-test_.cc +++ b/googletest/test/googletest-param-test-invalid-name1-test_.cc @@ -26,8 +26,7 @@ // 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: jmadill@google.com (Jamie Madill) + #include "gtest/gtest.h" diff --git a/googletest/test/googletest-param-test-invalid-name2-test_.cc b/googletest/test/googletest-param-test-invalid-name2-test_.cc index 9a8ec4e..ef09349 100644 --- a/googletest/test/googletest-param-test-invalid-name2-test_.cc +++ b/googletest/test/googletest-param-test-invalid-name2-test_.cc @@ -26,8 +26,7 @@ // 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: jmadill@google.com (Jamie Madill) + #include "gtest/gtest.h" diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc index 893b132..d06b4df 100644 --- a/googletest/test/googletest-param-test-test.cc +++ b/googletest/test/googletest-param-test-test.cc @@ -26,8 +26,7 @@ // 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. This file verifies that the parameter // generators objects produce correct parameter sequences and that diff --git a/googletest/test/googletest-param-test-test.h b/googletest/test/googletest-param-test-test.h index ea1e884..632a61f 100644 --- a/googletest/test/googletest-param-test-test.h +++ b/googletest/test/googletest-param-test-test.h @@ -27,8 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// Authors: vladl@google.com (Vlad Losev) -// // The Google C++ Testing and Mocking Framework (Google Test) // // This header file provides classes and functions used internally diff --git a/googletest/test/googletest-param-test2-test.cc b/googletest/test/googletest-param-test2-test.cc index c562ff0..25bb945 100644 --- a/googletest/test/googletest-param-test2-test.cc +++ b/googletest/test/googletest-param-test2-test.cc @@ -26,8 +26,7 @@ // 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. This verifies that the basic constructs of // Google Test work. diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc index 32e893f..53afe93 100644 --- a/googletest/test/googletest-port-test.cc +++ b/googletest/test/googletest-port-test.cc @@ -27,8 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// Authors: vladl@google.com (Vlad Losev), wan@google.com (Zhanyong Wan) -// // This file tests the internal cross-platform support utilities. #include diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index e4bb0c2..ea8369d 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Google Test - The Google C++ Testing and Mocking Framework // diff --git a/googletest/test/googletest-shuffle-test_.cc b/googletest/test/googletest-shuffle-test_.cc index 6fb441b..1fe5f6a 100644 --- a/googletest/test/googletest-shuffle-test_.cc +++ b/googletest/test/googletest-shuffle-test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Verifies that test shuffling works. diff --git a/googletest/test/googletest-test-part-test.cc b/googletest/test/googletest-test-part-test.cc index ca8ba93..34e8022 100644 --- a/googletest/test/googletest-test-part-test.cc +++ b/googletest/test/googletest-test-part-test.cc @@ -26,9 +26,6 @@ // 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: mheule@google.com (Markus Heule) -// #include "gtest/gtest-test-part.h" diff --git a/googletest/test/googletest-test2_test.cc b/googletest/test/googletest-test2_test.cc index 0a758c7..c2f98dc 100644 --- a/googletest/test/googletest-test2_test.cc +++ b/googletest/test/googletest-test2_test.cc @@ -26,8 +26,7 @@ // 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. This verifies that the basic constructs of // Google Test work. diff --git a/googletest/test/googletest-throw-on-failure-test_.cc b/googletest/test/googletest-throw-on-failure-test_.cc index 0617c27..f9a2c64 100644 --- a/googletest/test/googletest-throw-on-failure-test_.cc +++ b/googletest/test/googletest-throw-on-failure-test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests Google Test's throw-on-failure mode with exceptions disabled. // diff --git a/googletest/test/googletest-tuple-test.cc b/googletest/test/googletest-tuple-test.cc index bfaa3e0..dd82c16 100644 --- a/googletest/test/googletest-tuple-test.cc +++ b/googletest/test/googletest-tuple-test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include "gtest/internal/gtest-tuple.h" #include diff --git a/googletest/test/googletest-uninitialized-test_.cc b/googletest/test/googletest-uninitialized-test_.cc index 2ba0e8b..b4434d5 100644 --- a/googletest/test/googletest-uninitialized-test_.cc +++ b/googletest/test/googletest-uninitialized-test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include "gtest/gtest.h" diff --git a/googletest/test/gtest-typed-test2_test.cc b/googletest/test/gtest-typed-test2_test.cc index c284700..ed96421 100644 --- a/googletest/test/gtest-typed-test2_test.cc +++ b/googletest/test/gtest-typed-test2_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include diff --git a/googletest/test/gtest-typed-test_test.cc b/googletest/test/gtest-typed-test_test.cc index 93628ba..eddb52b 100644 --- a/googletest/test/gtest-typed-test_test.cc +++ b/googletest/test/gtest-typed-test_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include "test/gtest-typed-test_test.h" diff --git a/googletest/test/gtest-typed-test_test.h b/googletest/test/gtest-typed-test_test.h index 41d7570..2cce67c 100644 --- a/googletest/test/gtest-typed-test_test.h +++ b/googletest/test/gtest-typed-test_test.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #ifndef GTEST_TEST_GTEST_TYPED_TEST_TEST_H_ #define GTEST_TEST_GTEST_TYPED_TEST_TEST_H_ diff --git a/googletest/test/gtest-unittest-api_test.cc b/googletest/test/gtest-unittest-api_test.cc index 1ebd431..f3ea03a 100644 --- a/googletest/test/gtest-unittest-api_test.cc +++ b/googletest/test/gtest-unittest-api_test.cc @@ -25,8 +25,7 @@ // 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) + // // The Google C++ Testing and Mocking Framework (Google Test) // diff --git a/googletest/test/gtest_all_test.cc b/googletest/test/gtest_all_test.cc index a9aba01..e61e36b 100644 --- a/googletest/test/gtest_all_test.cc +++ b/googletest/test/gtest_all_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests for Google C++ Testing and Mocking Framework (Google Test) // diff --git a/googletest/test/gtest_assert_by_exception_test.cc b/googletest/test/gtest_assert_by_exception_test.cc index 2f0e34a..8d74d60 100644 --- a/googletest/test/gtest_assert_by_exception_test.cc +++ b/googletest/test/gtest_assert_by_exception_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests Google Test's assert-by-exception mode with exceptions enabled. diff --git a/googletest/test/gtest_environment_test.cc b/googletest/test/gtest_environment_test.cc index 1d6dc12..bc9524d 100644 --- a/googletest/test/gtest_environment_test.cc +++ b/googletest/test/gtest_environment_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests using global test environments. diff --git a/googletest/test/gtest_help_test_.cc b/googletest/test/gtest_help_test_.cc index 31f78c2..750ae6c 100644 --- a/googletest/test/gtest_help_test_.cc +++ b/googletest/test/gtest_help_test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // This program is meant to be run by gtest_help_test.py. Do not run // it directly. diff --git a/googletest/test/gtest_main_unittest.cc b/googletest/test/gtest_main_unittest.cc index c979fce..eddedea 100644 --- a/googletest/test/gtest_main_unittest.cc +++ b/googletest/test/gtest_main_unittest.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include "gtest/gtest.h" diff --git a/googletest/test/gtest_no_test_unittest.cc b/googletest/test/gtest_no_test_unittest.cc index 292599a..d4f88db 100644 --- a/googletest/test/gtest_no_test_unittest.cc +++ b/googletest/test/gtest_no_test_unittest.cc @@ -29,8 +29,6 @@ // Tests that a Google Test program that has no test defined can run // successfully. -// -// Author: wan@google.com (Zhanyong Wan) #include "gtest/gtest.h" diff --git a/googletest/test/gtest_premature_exit_test.cc b/googletest/test/gtest_premature_exit_test.cc index 3b4dc7d..c1e9305 100644 --- a/googletest/test/gtest_premature_exit_test.cc +++ b/googletest/test/gtest_premature_exit_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests that Google Test manipulates the premature-exit-detection // file correctly. diff --git a/googletest/test/gtest_prod_test.cc b/googletest/test/gtest_prod_test.cc index c5cceab..ede81a0 100644 --- a/googletest/test/gtest_prod_test.cc +++ b/googletest/test/gtest_prod_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Unit test for gtest_prod.h. diff --git a/googletest/test/gtest_repeat_test.cc b/googletest/test/gtest_repeat_test.cc index 3171604..e2888a5 100644 --- a/googletest/test/gtest_repeat_test.cc +++ b/googletest/test/gtest_repeat_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests the --gtest_repeat=number flag. diff --git a/googletest/test/gtest_sole_header_test.cc b/googletest/test/gtest_sole_header_test.cc index ccd091a..1d94ac6 100644 --- a/googletest/test/gtest_sole_header_test.cc +++ b/googletest/test/gtest_sole_header_test.cc @@ -26,8 +26,7 @@ // 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: mheule@google.com (Markus Heule) + // // This test verifies that it's possible to use Google Test by including // the gtest.h header file alone. diff --git a/googletest/test/gtest_stress_test.cc b/googletest/test/gtest_stress_test.cc index cac405f..95ada39 100644 --- a/googletest/test/gtest_stress_test.cc +++ b/googletest/test/gtest_stress_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests that SCOPED_TRACE() and various Google Test assertions can be // used in a large number of threads concurrently. diff --git a/googletest/test/gtest_test_macro_stack_footprint_test.cc b/googletest/test/gtest_test_macro_stack_footprint_test.cc index 48958b8..a48db05 100644 --- a/googletest/test/gtest_test_macro_stack_footprint_test.cc +++ b/googletest/test/gtest_test_macro_stack_footprint_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Each TEST() expands to some static registration logic. GCC puts all // such static initialization logic for a translation unit in a common, diff --git a/googletest/test/gtest_testbridge_test_.cc b/googletest/test/gtest_testbridge_test_.cc index 0bb069e..24617b2 100644 --- a/googletest/test/gtest_testbridge_test_.cc +++ b/googletest/test/gtest_testbridge_test_.cc @@ -26,8 +26,7 @@ // 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: rfj@google.com (Rohan Joyce) + // This program is meant to be run by gtest_test_filter_test.py. Do not run // it directly. diff --git a/googletest/test/gtest_throw_on_failure_ex_test.cc b/googletest/test/gtest_throw_on_failure_ex_test.cc index 8d46c76..93f59d4 100644 --- a/googletest/test/gtest_throw_on_failure_ex_test.cc +++ b/googletest/test/gtest_throw_on_failure_ex_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests Google Test's throw-on-failure mode with exceptions enabled. diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 033bc3a..f7acde2 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests for Google Test itself. This verifies that the basic constructs of // Google Test work. diff --git a/googletest/test/gtest_xml_outfile1_test_.cc b/googletest/test/gtest_xml_outfile1_test_.cc index e3d1dd1..a38ebac 100644 --- a/googletest/test/gtest_xml_outfile1_test_.cc +++ b/googletest/test/gtest_xml_outfile1_test_.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// // gtest_xml_outfile1_test_ writes some xml via TestProperty used by // gtest_xml_outfiles_test.py diff --git a/googletest/test/gtest_xml_outfile2_test_.cc b/googletest/test/gtest_xml_outfile2_test_.cc index 55eb8f3..afaf15a 100644 --- a/googletest/test/gtest_xml_outfile2_test_.cc +++ b/googletest/test/gtest_xml_outfile2_test_.cc @@ -27,7 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// // gtest_xml_outfile2_test_ writes some xml via TestProperty used by // gtest_xml_outfiles_test.py diff --git a/googletest/test/production.cc b/googletest/test/production.cc index 006bb97..0f69f6d 100644 --- a/googletest/test/production.cc +++ b/googletest/test/production.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // This is part of the unit test for gtest_prod.h. diff --git a/googletest/test/production.h b/googletest/test/production.h index 0f01d83..542723b 100644 --- a/googletest/test/production.h +++ b/googletest/test/production.h @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // This is part of the unit test for gtest_prod.h. -- cgit v0.12 From 265efde9a5b35fbd23622620fa597822e122f38a Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Tue, 14 Aug 2018 15:04:11 -0400 Subject: Comments changes, no functionality changes. --- googlemock/include/gmock/gmock-matchers.h | 6 ++--- googlemock/include/gmock/gmock-spec-builders.h | 4 +-- .../include/gmock/internal/gmock-internal-utils.h | 2 +- googlemock/test/gmock-actions_test.cc | 2 +- googlemock/test/gmock-spec-builders_test.cc | 2 +- googlemock/test/gmock_leak_test.py | 2 -- googlemock/test/gmock_output_test.py | 2 -- googlemock/test/gmock_test_utils.py | 2 -- googletest/include/gtest/gtest-death-test.h | 2 +- googletest/include/gtest/gtest-printers.h | 2 +- googletest/include/gtest/gtest.h | 4 +-- .../include/gtest/internal/gtest-linked_ptr.h | 2 +- googletest/include/gtest/internal/gtest-port.h | 10 ++++---- googletest/include/gtest/internal/gtest-tuple.h | 2 +- .../include/gtest/internal/gtest-tuple.h.pump | 2 +- googletest/src/gtest-death-test.cc | 4 +-- googletest/src/gtest-filepath.cc | 4 +-- googletest/src/gtest-internal-inl.h | 2 +- googletest/src/gtest-port.cc | 6 ++--- googletest/src/gtest-printers.cc | 2 +- googletest/src/gtest.cc | 30 +++++++++++----------- .../test/googletest-break-on-failure-unittest.py | 2 -- .../test/googletest-catch-exceptions-test.py | 2 -- googletest/test/googletest-color-test.py | 2 -- googletest/test/googletest-death-test-test.cc | 2 +- googletest/test/googletest-env-var-test.py | 2 -- googletest/test/googletest-filepath-test.cc | 2 +- googletest/test/googletest-filter-unittest.py | 2 -- googletest/test/googletest-json-outfiles-test.py | 4 +-- googletest/test/googletest-list-tests-unittest.py | 2 -- googletest/test/googletest-options-test.cc | 2 +- googletest/test/googletest-output-test.py | 4 +-- .../googletest-param-test-invalid-name1-test.py | 2 -- .../googletest-param-test-invalid-name2-test.py | 2 -- googletest/test/googletest-param-test-test.cc | 2 +- googletest/test/googletest-port-test.cc | 2 +- googletest/test/googletest-shuffle-test.py | 2 -- googletest/test/googletest-test-part-test.cc | 2 +- .../test/googletest-throw-on-failure-test.py | 4 +-- googletest/test/googletest-uninitialized-test.py | 2 -- googletest/test/gtest_assert_by_exception_test.cc | 2 +- googletest/test/gtest_help_test.py | 2 -- googletest/test/gtest_repeat_test.cc | 2 +- googletest/test/gtest_test_utils.py | 4 +-- googletest/test/gtest_testbridge_test.py | 2 -- googletest/test/gtest_unittest.cc | 5 ++-- googletest/test/gtest_xml_outfiles_test.py | 4 +-- 47 files changed, 61 insertions(+), 98 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 490f3a4..a001850 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -73,7 +73,7 @@ namespace testing { // MatchResultListener is an abstract class. Its << operator can be // used by a matcher to explain why a value matches or doesn't match. // -// TODO(wan@google.com): add method +// FIXME: add method // bool InterestedInWhy(bool result) const; // to indicate whether the listener is interested in why the match // result is 'result'. @@ -922,7 +922,7 @@ class TuplePrefix { GTEST_REFERENCE_TO_CONST_(Value) value = get(values); StringMatchResultListener listener; if (!matcher.MatchAndExplain(value, &listener)) { - // TODO(wan): include in the message the name of the parameter + // FIXME: include in the message the name of the parameter // as used in MOCK_METHOD*() when possible. *os << " Expected arg #" << N - 1 << ": "; get(matchers).DescribeTo(os); @@ -2420,7 +2420,7 @@ class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase { template bool MatchAndExplain(From from, MatchResultListener* listener) const { - // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail? + // FIXME: Add more detail on failures. ie did the dyn_cast fail? To to = dynamic_cast(from); return MatchPrintAndExplain(to, this->matcher_, listener); } diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index f49d01f..0d83cd6 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -184,7 +184,7 @@ class GTEST_API_ UntypedFunctionMockerBase { // this information in the global mock registry. Will be called // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock // method. - // TODO(wan@google.com): rename to SetAndRegisterOwner(). + // FIXME: rename to SetAndRegisterOwner(). void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); @@ -1207,7 +1207,7 @@ class TypedExpectation : public ExpectationBase { mocker->DescribeDefaultActionTo(args, what); DescribeCallCountTo(why); - // TODO(wan@google.com): allow the user to control whether + // FIXME: allow the user to control whether // unexpected calls should fail immediately or continue using a // flag --gmock_unexpected_calls_are_fatal. return NULL; diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index b020f89..db64c65 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -360,7 +360,7 @@ class WithoutMatchers { // Internal use only: access the singleton instance of WithoutMatchers. GTEST_API_ WithoutMatchers GetWithoutMatchers(); -// TODO(wan@google.com): group all type utilities together. +// FIXME: group all type utilities together. // Type traits. diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index e216fe2..06e29a1 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -1343,7 +1343,7 @@ TEST(FunctorActionTest, UnusedArguments) { } // Test that basic built-in actions work with move-only arguments. -// TODO(rburny): Currently, almost all ActionInterface-based actions will not +// FIXME: Currently, almost all ActionInterface-based actions will not // work, even if they only try to use other, copyable arguments. Implement them // if necessary (but note that DoAll cannot work on non-copyable types anyway - // so maybe it's better to make users use lambdas instead. diff --git a/googlemock/test/gmock-spec-builders_test.cc b/googlemock/test/gmock-spec-builders_test.cc index 78fbc3f..7056c43 100644 --- a/googlemock/test/gmock-spec-builders_test.cc +++ b/googlemock/test/gmock-spec-builders_test.cc @@ -1175,7 +1175,7 @@ TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) { TEST(UndefinedReturnValueTest, ReturnValueIsMandatoryWhenNotDefaultConstructible) { MockA a; - // TODO(wan@google.com): We should really verify the output message, + // FIXME: We should really verify the output message, // but we cannot yet due to that EXPECT_DEATH only captures stderr // while Google Mock logs to stdout. #if GTEST_HAS_EXCEPTIONS diff --git a/googlemock/test/gmock_leak_test.py b/googlemock/test/gmock_leak_test.py index a2fee4b..7e4b1ee 100755 --- a/googlemock/test/gmock_leak_test.py +++ b/googlemock/test/gmock_leak_test.py @@ -31,8 +31,6 @@ """Tests that leaked mock objects can be caught be Google Mock.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - import gmock_test_utils PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_') diff --git a/googlemock/test/gmock_output_test.py b/googlemock/test/gmock_output_test.py index 20323e1..0527bd9 100755 --- a/googlemock/test/gmock_output_test.py +++ b/googlemock/test/gmock_output_test.py @@ -39,8 +39,6 @@ gmock_output_test.py """ -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import re import sys diff --git a/googlemock/test/gmock_test_utils.py b/googlemock/test/gmock_test_utils.py index 92b1ac1..7dc4e11 100755 --- a/googlemock/test/gmock_test_utils.py +++ b/googlemock/test/gmock_test_utils.py @@ -29,8 +29,6 @@ """Unit test utilities for Google C++ Mocking Framework.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import sys diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h index 06fe42e..20c54d8 100644 --- a/googletest/include/gtest/gtest-death-test.h +++ b/googletest/include/gtest/gtest-death-test.h @@ -161,7 +161,7 @@ GTEST_API_ bool InDeathTestChild(); // is rarely a problem as people usually don't put the test binary // directory in PATH. // -// TODO(wan@google.com): make thread-safe death tests search the PATH. +// FIXME: make thread-safe death tests search the PATH. // Asserts that a given statement causes the program to exit, with an // integer exit status that satisfies predicate, and emitting error output diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index f4accac..c67e30a 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -826,7 +826,7 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { // If the array has more than kThreshold elements, we'll have to // omit some details by printing only the first and the last // kChunkSize elements. - // TODO(wan@google.com): let the user control the threshold using a flag. + // FIXME: let the user control the threshold using a flag. if (len <= kThreshold) { PrintRawArrayTo(begin, len, os); } else { diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index f374c59..65bd9cb 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -315,7 +315,7 @@ class GTEST_API_ AssertionResult { const char* message() const { return message_.get() != NULL ? message_->c_str() : ""; } - // TODO(vladl@google.com): Remove this after making sure no clients use it. + // FIXME: Remove this after making sure no clients use it. // Deprecated; please use message() instead. const char* failure_message() const { return message(); } @@ -621,7 +621,7 @@ class GTEST_API_ TestResult { // Adds a failure if the key is a reserved attribute of Google Test // testcase tags. Returns true if the property is valid. - // TODO(russr): Validate attribute names are legal and human readable. + // FIXME: Validate attribute names are legal and human readable. static bool ValidateTestProperty(const std::string& xml_element, const TestProperty& test_property); diff --git a/googletest/include/gtest/internal/gtest-linked_ptr.h b/googletest/include/gtest/internal/gtest-linked_ptr.h index fa2c3b3..082b872 100644 --- a/googletest/include/gtest/internal/gtest-linked_ptr.h +++ b/googletest/include/gtest/internal/gtest-linked_ptr.h @@ -60,7 +60,7 @@ // raw pointer (e.g. via get()) concurrently, and // - it's safe to write to two linked_ptrs that point to the same // shared object concurrently. -// TODO(wan@google.com): rename this to safe_linked_ptr to avoid +// FIXME: rename this to safe_linked_ptr to avoid // confusion with normal linked_ptr. // GOOGLETEST_CM0001 DO NOT DELETE diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 5d96a05..a0d318c 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -547,7 +547,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #ifndef GTEST_HAS_STD_WSTRING // The user didn't tell us whether ::std::wstring is available, so we need // to figure it out. -// TODO(wan@google.com): uses autoconf to detect whether ::std::wstring +// FIXME: uses autoconf to detect whether ::std::wstring // is available. // Cygwin 1.7 and below doesn't support ::std::wstring. @@ -759,7 +759,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Until version 4.3.2, gcc has a bug that causes , // which is #included by , to not compile when RTTI is // disabled. _TR1_FUNCTIONAL is the header guard for -// . Hence the following #define is a hack to prevent +// . Hence the following #define is used to prevent // from being included. # define _TR1_FUNCTIONAL 1 # include @@ -1264,7 +1264,7 @@ class GTEST_API_ RE { // PartialMatch(str, re) returns true iff regular expression re // matches a substring of str (including str itself). // - // TODO(wan@google.com): make FullMatch() and PartialMatch() work + // FIXME: make FullMatch() and PartialMatch() work // when str contains NUL characters. static bool FullMatch(const ::std::string& str, const RE& re) { return FullMatch(str.c_str(), re); @@ -1291,7 +1291,7 @@ class GTEST_API_ RE { void Init(const char* regex); // We use a const char* instead of an std::string, as Google Test used to be - // used where std::string is not available. TODO(wan@google.com): change to + // used where std::string is not available. FIXME: change to // std::string. const char* pattern_; bool is_valid_; @@ -2684,7 +2684,7 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. // Parses 'str' for a 32-bit signed integer. If successful, writes the result // to *value and returns true; otherwise leaves *value unchanged and returns // false. -// TODO(chandlerc): Find a better way to refactor flag and environment parsing +// FIXME: Find a better way to refactor flag and environment parsing // out of both gtest-port.cc and gtest.cc to avoid exporting this utility // function. bool ParseInt32(const Message& src_text, const char* str, Int32* value); diff --git a/googletest/include/gtest/internal/gtest-tuple.h b/googletest/include/gtest/internal/gtest-tuple.h index 89748cc..78a3a6a 100644 --- a/googletest/include/gtest/internal/gtest-tuple.h +++ b/googletest/include/gtest/internal/gtest-tuple.h @@ -43,7 +43,7 @@ // The compiler used in Symbian has a bug that prevents us from declaring the // tuple template as a friend (it complains that tuple is redefined). This -// hack bypasses the bug by declaring the members that should otherwise be +// bypasses the bug by declaring the members that should otherwise be // private as public. // Sun Studio versions < 12 also have the above bug. #if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) diff --git a/googletest/include/gtest/internal/gtest-tuple.h.pump b/googletest/include/gtest/internal/gtest-tuple.h.pump index a08bf70..bb626e0 100644 --- a/googletest/include/gtest/internal/gtest-tuple.h.pump +++ b/googletest/include/gtest/internal/gtest-tuple.h.pump @@ -42,7 +42,7 @@ $$ This meta comment fixes auto-indentation in Emacs. }} // The compiler used in Symbian has a bug that prevents us from declaring the // tuple template as a friend (it complains that tuple is redefined). This -// hack bypasses the bug by declaring the members that should otherwise be +// bypasses the bug by declaring the members that should otherwise be // private as public. // Sun Studio versions < 12 also have the above bug. #if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 97dbffc..0908355 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -266,7 +266,7 @@ static const int kFuchsiaReadPipeFd = 3; // statement, which is not allowed; THREW means that the test statement // returned control by throwing an exception. IN_PROGRESS means the test // has not yet concluded. -// TODO(vladl@google.com): Unify names and possibly values for +// FIXME: Unify names and possibly values for // AbortReason, DeathTestOutcome, and flag characters above. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; @@ -1458,7 +1458,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id, StreamableToString(parent_process_id)); } - // TODO(vladl@google.com): Replace the following check with a + // FIXME: Replace the following check with a // compile-time assertion when available. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc index 6b76ea0..a7e65c0 100644 --- a/googletest/src/gtest-filepath.cc +++ b/googletest/src/gtest-filepath.cc @@ -250,7 +250,7 @@ bool FilePath::DirectoryExists() const { // root directory per disk drive.) bool FilePath::IsRootDirectory() const { #if GTEST_OS_WINDOWS - // TODO(wan@google.com): on Windows a network share like + // FIXME: on Windows a network share like // \\server\share can be a root directory, although it cannot be the // current directory. Handle this properly. return pathname_.length() == 3 && IsAbsolutePath(); @@ -350,7 +350,7 @@ FilePath FilePath::RemoveTrailingPathSeparator() const { // Removes any redundant separators that might be in the pathname. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other // redundancies that might be in a pathname involving "." or "..". -// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share). +// FIXME: handle Windows network shares (e.g. \\server\share). void FilePath::Normalize() { if (pathname_.c_str() == NULL) { pathname_ = ""; diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index f7ed9a1..43effbf 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -991,7 +991,7 @@ bool ParseNaturalNumber(const ::std::string& str, Integer* number) { const bool parse_success = *end == '\0' && errno == 0; - // TODO(vladl@google.com): Convert this to compile time assertion when it is + // FIXME: Convert this to compile time assertion when it is // available. GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index 0b49193..13901e3 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -261,7 +261,7 @@ Mutex::Mutex() Mutex::~Mutex() { // Static mutexes are leaked intentionally. It is not thread-safe to try // to clean them up. - // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires + // FIXME: Switch to Slim Reader/Writer (SRW) Locks, which requires // nothing to clean it up but is available only on Vista and later. // https://docs.microsoft.com/en-us/windows/desktop/Sync/slim-reader-writer--srw--locks if (type_ == kDynamic) { @@ -343,7 +343,7 @@ class ThreadWithParamSupport : public ThreadWithParamBase { Notification* thread_can_start) { ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start); DWORD thread_id; - // TODO(yukawa): Consider to use _beginthreadex instead. + // FIXME: Consider to use _beginthreadex instead. HANDLE thread_handle = ::CreateThread( NULL, // Default security. 0, // Default stack size. @@ -695,7 +695,7 @@ static std::string FormatRegexSyntaxError(const char* regex, int index) { // otherwise returns true. bool ValidateRegex(const char* regex) { if (regex == NULL) { - // TODO(wan@google.com): fix the source file location in the + // FIXME: fix the source file location in the // assertion failures to match where the regex is used in user // code. ADD_FAILURE() << "NULL is not a valid simple regular expression."; diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc index d68d929..de4d245 100644 --- a/googletest/src/gtest-printers.cc +++ b/googletest/src/gtest-printers.cc @@ -89,7 +89,7 @@ void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, // If the object size is bigger than kThreshold, we'll have to omit // some details by printing only the first and the last kChunkSize // bytes. - // TODO(wan): let the user control the threshold using a flag. + // FIXME: let the user control the threshold using a flag. if (count < kThreshold) { PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); } else { diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 37e5b1f..2bcdfd1 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -54,7 +54,7 @@ #if GTEST_OS_LINUX -// TODO(kenton@google.com): Use autoconf to detect availability of +// FIXME: Use autoconf to detect availability of // gettimeofday(). # define GTEST_HAS_GETTIMEOFDAY_ 1 @@ -93,9 +93,9 @@ # if GTEST_OS_WINDOWS_MINGW // MinGW has gettimeofday() but not _ftime64(). -// TODO(kenton@google.com): Use autoconf to detect availability of +// FIXME: Use autoconf to detect availability of // gettimeofday(). -// TODO(kenton@google.com): There are other ways to get the time on +// FIXME: There are other ways to get the time on // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW // supports these. consider using them instead. # define GTEST_HAS_GETTIMEOFDAY_ 1 @@ -110,7 +110,7 @@ #else // Assume other platforms have gettimeofday(). -// TODO(kenton@google.com): Use autoconf to detect availability of +// FIXME: Use autoconf to detect availability of // gettimeofday(). # define GTEST_HAS_GETTIMEOFDAY_ 1 @@ -467,7 +467,7 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() { internal::FilePath output_name(colon + 1); if (!output_name.IsAbsolutePath()) - // TODO(wan@google.com): on Windows \some\path is not an absolute + // FIXME: on Windows \some\path is not an absolute // path (as its meaning depends on the current drive), yet the // following logic for turning it into an absolute path is wrong. // Fix it. @@ -841,7 +841,7 @@ TimeInMillis GetTimeInMillis() { SYSTEMTIME now_systime; FILETIME now_filetime; ULARGE_INTEGER now_int64; - // TODO(kenton@google.com): Shouldn't this just use + // FIXME: Shouldn't this just use // GetSystemTimeAsFileTime()? GetSystemTime(&now_systime); if (SystemTimeToFileTime(&now_systime, &now_filetime)) { @@ -857,7 +857,7 @@ TimeInMillis GetTimeInMillis() { // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 // (deprecated function) there. - // TODO(kenton@google.com): Use GetTickCount()? Or use + // FIXME: Use GetTickCount()? Or use // SystemTimeToFileTime() GTEST_DISABLE_MSC_DEPRECATED_PUSH_() _ftime64(&now); @@ -1396,7 +1396,7 @@ AssertionResult DoubleNearPredFormat(const char* expr1, const double diff = fabs(val1 - val2); if (diff <= abs_error) return AssertionSuccess(); - // TODO(wan): do not print the value of an expression if it's + // FIXME: do not print the value of an expression if it's // already a literal. return AssertionFailure() << "The difference between " << expr1 << " and " << expr2 @@ -3334,7 +3334,7 @@ void TestEventRepeater::Append(TestEventListener *listener) { listeners_.push_back(listener); } -// TODO(vladl@google.com): Factor the search functionality into Vector::Find. +// FIXME: Factor the search functionality into Vector::Find. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { for (size_t i = 0; i < listeners_.size(); ++i) { if (listeners_[i] == listener) { @@ -3499,7 +3499,7 @@ void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, xmlout = posix::FOpen(output_file_.c_str(), "w"); } if (xmlout == NULL) { - // TODO(wan): report the reason of the failure. + // FIXME: report the reason of the failure. // // We don't do it for now as: // @@ -3528,7 +3528,7 @@ void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, // module will consist of ordinary English text. // If this module is ever modified to produce version 1.1 XML output, // most invalid characters can be retained using character references. -// TODO(wan): It might be nice to have a minimally invasive, human-readable +// FIXME: It might be nice to have a minimally invasive, human-readable // escaping scheme for invalid characters, rather than dropping them. std::string XmlUnitTestResultPrinter::EscapeXml( const std::string& str, bool is_attribute) { @@ -3679,7 +3679,7 @@ void XmlUnitTestResultPrinter::OutputXmlAttribute( } // Prints an XML representation of a TestInfo object. -// TODO(wan): There is also value in printing properties with the plain printer. +// FIXME: There is also value in printing properties with the plain printer. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, const char* test_case_name, const TestInfo& test_info) { @@ -3906,7 +3906,7 @@ void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, jsonout = posix::FOpen(output_file_.c_str(), "w"); } if (jsonout == NULL) { - // TODO(phosek): report the reason of the failure. + // FIXME: report the reason of the failure. // // We don't do it for now as: // @@ -4721,7 +4721,7 @@ int UnitTest::Run() { // VC++ doesn't define _set_abort_behavior() prior to the version 8.0. // Users of prior VC versions shall suffer the agony and pain of // clicking through the countless debug dialogs. - // TODO(vladl@google.com): find a way to suppress the abort dialog() in the + // FIXME: find a way to suppress the abort dialog() in the // debug mode when compiled with VC 7.1 or lower. if (!GTEST_FLAG(break_on_failure)) _set_abort_behavior( @@ -5615,7 +5615,7 @@ static bool HasGoogleTestFlagPrefix(const char* str) { // @Y changes the color to yellow. // @D changes to the default terminal text color. // -// TODO(wan@google.com): Write tests for this once we add stdout +// FIXME: Write tests for this once we add stdout // capturing to Google Test. static void PrintColorEncoded(const char* str) { GTestColor color = COLOR_DEFAULT; // The current color. diff --git a/googletest/test/googletest-break-on-failure-unittest.py b/googletest/test/googletest-break-on-failure-unittest.py index cd77547..a5dfbc6 100755 --- a/googletest/test/googletest-break-on-failure-unittest.py +++ b/googletest/test/googletest-break-on-failure-unittest.py @@ -38,8 +38,6 @@ by invoking googletest-break-on-failure-unittest_ (a program written with Google Test) with different environments and command line flags. """ -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import gtest_test_utils diff --git a/googletest/test/googletest-catch-exceptions-test.py b/googletest/test/googletest-catch-exceptions-test.py index 69dbadf..5d49c10 100755 --- a/googletest/test/googletest-catch-exceptions-test.py +++ b/googletest/test/googletest-catch-exceptions-test.py @@ -35,8 +35,6 @@ googletest-catch-exceptions-ex-test_ (programs written with Google Test) and verifies their output. """ -__author__ = 'vladl@google.com (Vlad Losev)' - import gtest_test_utils # Constants. diff --git a/googletest/test/googletest-color-test.py b/googletest/test/googletest-color-test.py index 875d478..f3b7c99 100755 --- a/googletest/test/googletest-color-test.py +++ b/googletest/test/googletest-color-test.py @@ -31,8 +31,6 @@ """Verifies that Google Test correctly determines whether to use colors.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import gtest_test_utils diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc index 0699029..c0c3026 100644 --- a/googletest/test/googletest-death-test-test.cc +++ b/googletest/test/googletest-death-test-test.cc @@ -1279,7 +1279,7 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) { # if GTEST_OS_WINDOWS TEST(EnvironmentTest, HandleFitsIntoSizeT) { - // TODO(vladl@google.com): Remove this test after this condition is verified + // FIXME: Remove this test after this condition is verified // in a static assertion in gtest-death-test.cc in the function // GetStatusFileDescriptor. ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t)); diff --git a/googletest/test/googletest-env-var-test.py b/googletest/test/googletest-env-var-test.py index 9c80e2a..e1efeee 100755 --- a/googletest/test/googletest-env-var-test.py +++ b/googletest/test/googletest-env-var-test.py @@ -31,8 +31,6 @@ """Verifies that Google Test correctly parses environment variables.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import gtest_test_utils diff --git a/googletest/test/googletest-filepath-test.cc b/googletest/test/googletest-filepath-test.cc index e832666..37f02fb 100644 --- a/googletest/test/googletest-filepath-test.cc +++ b/googletest/test/googletest-filepath-test.cc @@ -50,7 +50,7 @@ namespace internal { namespace { #if GTEST_OS_WINDOWS_MOBILE -// TODO(wan@google.com): Move these to the POSIX adapter section in +// FIXME: Move these to the POSIX adapter section in // gtest-port.h. // Windows CE doesn't have the remove C function. diff --git a/googletest/test/googletest-filter-unittest.py b/googletest/test/googletest-filter-unittest.py index 1e554d5..dc0b5bd 100755 --- a/googletest/test/googletest-filter-unittest.py +++ b/googletest/test/googletest-filter-unittest.py @@ -40,8 +40,6 @@ Note that test sharding may also influence which tests are filtered. Therefore, we test that here also. """ -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import re import sets diff --git a/googletest/test/googletest-json-outfiles-test.py b/googletest/test/googletest-json-outfiles-test.py index 46010d8..c99be48 100644 --- a/googletest/test/googletest-json-outfiles-test.py +++ b/googletest/test/googletest-json-outfiles-test.py @@ -136,11 +136,11 @@ class GTestJsonOutFilesTest(gtest_test_utils.TestCase): self.assert_(p.exited) self.assertEquals(0, p.exit_code) - # TODO(wan@google.com): libtool causes the built test binary to be + # FIXME: libtool causes the built test binary to be # named lt-gtest_xml_outfiles_test_ instead of # gtest_xml_outfiles_test_. To account for this possibility, we # allow both names in the following code. We should remove this - # hack when Chandler Carruth's libtool replacement tool is ready. + # when libtool replacement tool is ready. output_file_name1 = test_name + '.json' output_file1 = os.path.join(self.output_dir_, output_file_name1) output_file_name2 = 'lt-' + output_file_name1 diff --git a/googletest/test/googletest-list-tests-unittest.py b/googletest/test/googletest-list-tests-unittest.py index a38073a..81423a3 100755 --- a/googletest/test/googletest-list-tests-unittest.py +++ b/googletest/test/googletest-list-tests-unittest.py @@ -37,8 +37,6 @@ by invoking googletest-list-tests-unittest_ (a program written with Google Test) the command line flags. """ -__author__ = 'phanna@google.com (Patrick Hanna)' - import re import gtest_test_utils diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc index e426ce2..bbda04f 100644 --- a/googletest/test/googletest-options-test.cc +++ b/googletest/test/googletest-options-test.cc @@ -105,7 +105,7 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { #elif GTEST_OS_FUCHSIA const bool success = exe_str == "app"; #else - // TODO(wan@google.com): remove the hard-coded "lt-" prefix when + // FIXME: remove the hard-coded "lt-" prefix when // Chandler Carruth's libtool replacement is ready. const bool success = exe_str == "googletest-options-test" || diff --git a/googletest/test/googletest-output-test.py b/googletest/test/googletest-output-test.py index 0dae8d1..2d69e35 100755 --- a/googletest/test/googletest-output-test.py +++ b/googletest/test/googletest-output-test.py @@ -38,8 +38,6 @@ googletest_output_test.py --gengolden googletest_output_test.py """ -__author__ = 'wan@google.com (Zhanyong Wan)' - import difflib import os import re @@ -57,7 +55,7 @@ NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' IS_WINDOWS = os.name == 'nt' -# TODO(vladl@google.com): remove the _lin suffix. +# FIXME: remove the _lin suffix. GOLDEN_NAME = 'googletest-output-test-golden-lin.txt' PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('googletest-output-test_') diff --git a/googletest/test/googletest-param-test-invalid-name1-test.py b/googletest/test/googletest-param-test-invalid-name1-test.py index a402c33..2a08477 100644 --- a/googletest/test/googletest-param-test-invalid-name1-test.py +++ b/googletest/test/googletest-param-test-invalid-name1-test.py @@ -30,8 +30,6 @@ """Verifies that Google Test warns the user when not initialized properly.""" -__author__ = 'jmadill@google.com (Jamie Madill)' - import gtest_test_utils binary_name = 'googletest-param-test-invalid-name1-test_' diff --git a/googletest/test/googletest-param-test-invalid-name2-test.py b/googletest/test/googletest-param-test-invalid-name2-test.py index 5766134..ab838f4 100644 --- a/googletest/test/googletest-param-test-invalid-name2-test.py +++ b/googletest/test/googletest-param-test-invalid-name2-test.py @@ -30,8 +30,6 @@ """Verifies that Google Test warns the user when not initialized properly.""" -__author__ = 'jmadill@google.com (Jamie Madill)' - import gtest_test_utils binary_name = 'googletest-param-test-invalid-name2-test_' diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc index d06b4df..f789cab 100644 --- a/googletest/test/googletest-param-test-test.cc +++ b/googletest/test/googletest-param-test-test.cc @@ -67,7 +67,7 @@ using ::testing::internal::UnitTestOptions; // Prints a value to a string. // -// TODO(wan@google.com): remove PrintValue() when we move matchers and +// FIXME: remove PrintValue() when we move matchers and // EXPECT_THAT() from Google Mock to Google Test. At that time, we // can write EXPECT_THAT(x, Eq(y)) to compare two tuples x and y, as // EXPECT_THAT() and the matchers know how to print tuples. diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc index 53afe93..399316f 100644 --- a/googletest/test/googletest-port-test.cc +++ b/googletest/test/googletest-port-test.cc @@ -224,7 +224,7 @@ TEST(ScopedPtrTest, DefinesElementType) { StaticAssertTypeEq::element_type>(); } -// TODO(vladl@google.com): Implement THE REST of scoped_ptr tests. +// FIXME: Implement THE REST of scoped_ptr tests. TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) { if (AlwaysFalse()) diff --git a/googletest/test/googletest-shuffle-test.py b/googletest/test/googletest-shuffle-test.py index 5ae9655..573cc5e 100755 --- a/googletest/test/googletest-shuffle-test.py +++ b/googletest/test/googletest-shuffle-test.py @@ -30,8 +30,6 @@ """Verifies that test shuffling works.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import gtest_test_utils diff --git a/googletest/test/googletest-test-part-test.cc b/googletest/test/googletest-test-part-test.cc index 34e8022..cd2d6f9 100644 --- a/googletest/test/googletest-test-part-test.cc +++ b/googletest/test/googletest-test-part-test.cc @@ -200,6 +200,6 @@ TEST_F(TestPartResultArrayDeathTest, DiesWhenIndexIsOutOfBound) { EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(1), ""); } -// TODO(mheule@google.com): Add a test for the class HasNewFatalFailureHelper. +// FIXME: Add a test for the class HasNewFatalFailureHelper. } // namespace diff --git a/googletest/test/googletest-throw-on-failure-test.py b/googletest/test/googletest-throw-on-failure-test.py index 26ba32b..46cb9f6 100755 --- a/googletest/test/googletest-throw-on-failure-test.py +++ b/googletest/test/googletest-throw-on-failure-test.py @@ -35,8 +35,6 @@ This script invokes googletest-throw-on-failure-test_ (a program written with Google Test) with different environments and command line flags. """ -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import gtest_test_utils @@ -75,7 +73,7 @@ def Run(command): return p.exited and p.exit_code == 0 -# The tests. TODO(wan@google.com): refactor the class to share common +# The tests. FIXME: refactor the class to share common # logic with code in googletest-break-on-failure-unittest.py. class ThrowOnFailureTest(gtest_test_utils.TestCase): """Tests the throw-on-failure mode.""" diff --git a/googletest/test/googletest-uninitialized-test.py b/googletest/test/googletest-uninitialized-test.py index e3df5fa..5b7d1e7 100755 --- a/googletest/test/googletest-uninitialized-test.py +++ b/googletest/test/googletest-uninitialized-test.py @@ -31,8 +31,6 @@ """Verifies that Google Test warns the user when not initialized properly.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - import gtest_test_utils COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-uninitialized-test_') diff --git a/googletest/test/gtest_assert_by_exception_test.cc b/googletest/test/gtest_assert_by_exception_test.cc index 8d74d60..0eae857 100644 --- a/googletest/test/gtest_assert_by_exception_test.cc +++ b/googletest/test/gtest_assert_by_exception_test.cc @@ -97,7 +97,7 @@ TEST(Test, Test) { int kTestForContinuingTest = 0; TEST(Test, Test2) { - // FIXME(sokolov): how to force Test2 to be after Test? + // FIXME: how to force Test2 to be after Test? kTestForContinuingTest = 1; } diff --git a/googletest/test/gtest_help_test.py b/googletest/test/gtest_help_test.py index 79ffbe4..582d24c 100755 --- a/googletest/test/gtest_help_test.py +++ b/googletest/test/gtest_help_test.py @@ -37,8 +37,6 @@ SYNOPSIS gtest_help_test.py """ -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import re import gtest_test_utils diff --git a/googletest/test/gtest_repeat_test.cc b/googletest/test/gtest_repeat_test.cc index e2888a5..204a091 100644 --- a/googletest/test/gtest_repeat_test.cc +++ b/googletest/test/gtest_repeat_test.cc @@ -117,7 +117,7 @@ const int kNumberOfParamTests = 10; class MyParamTest : public testing::TestWithParam {}; TEST_P(MyParamTest, ShouldPass) { - // TODO(vladl@google.com): Make parameter value checking robust + // FIXME: Make parameter value checking robust // WRT order of tests. GTEST_CHECK_INT_EQ_(g_param_test_count % kNumberOfParamTests, GetParam()); g_param_test_count++; diff --git a/googletest/test/gtest_test_utils.py b/googletest/test/gtest_test_utils.py index c4c0227..43cba8f 100755 --- a/googletest/test/gtest_test_utils.py +++ b/googletest/test/gtest_test_utils.py @@ -31,8 +31,6 @@ # Suppresses the 'Import not at the top of the file' lint complaint. # pylint: disable-msg=C6204 -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import sys @@ -308,7 +306,7 @@ def Main(): _ParseAndStripGTestFlags(sys.argv) # The tested binaries should not be writing XML output files unless the # script explicitly instructs them to. - # TODO(vladl@google.com): Move this into Subprocess when we implement + # FIXME: Move this into Subprocess when we implement # passing environment into it as a parameter. if GTEST_OUTPUT_VAR_NAME in os.environ: del os.environ[GTEST_OUTPUT_VAR_NAME] diff --git a/googletest/test/gtest_testbridge_test.py b/googletest/test/gtest_testbridge_test.py index 2075e12..87ffad7 100755 --- a/googletest/test/gtest_testbridge_test.py +++ b/googletest/test/gtest_testbridge_test.py @@ -29,8 +29,6 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Verifies that Google Test uses filter provided via testbridge.""" -__author__ = 'rfj@google.com (Rohan Joyce)' - import os import gtest_test_utils diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index f7acde2..e1c30f3 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -1384,8 +1384,7 @@ class TestResultTest : public Test { // In order to test TestResult, we need to modify its internal // state, in particular the TestPartResult vector it holds. // test_part_results() returns a const reference to this vector. - // We cast it to a non-const object s.t. it can be modified (yes, - // this is a hack). + // We cast it to a non-const object s.t. it can be modified TPRVector* results1 = const_cast( &TestResultAccessor::test_part_results(*r1)); TPRVector* results2 = const_cast( @@ -7372,7 +7371,7 @@ GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST. // Tests for internal utilities necessary for implementation of the universal // printing. -// TODO(vladl@google.com): Find a better home for them. +// FIXME: Find a better home for them. class ConversionHelperBase {}; class ConversionHelperDerived : public ConversionHelperBase {}; diff --git a/googletest/test/gtest_xml_outfiles_test.py b/googletest/test/gtest_xml_outfiles_test.py index c7d3413..2c031ff 100755 --- a/googletest/test/gtest_xml_outfiles_test.py +++ b/googletest/test/gtest_xml_outfiles_test.py @@ -111,11 +111,11 @@ class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase): self.assert_(p.exited) self.assertEquals(0, p.exit_code) - # TODO(wan@google.com): libtool causes the built test binary to be + # FIXME: libtool causes the built test binary to be # named lt-gtest_xml_outfiles_test_ instead of # gtest_xml_outfiles_test_. To account for this possibility, we # allow both names in the following code. We should remove this - # hack when Chandler Carruth's libtool replacement tool is ready. + # when libtool replacement tool is ready. output_file_name1 = test_name + ".xml" output_file1 = os.path.join(self.output_dir_, output_file_name1) output_file_name2 = 'lt-' + output_file_name1 -- cgit v0.12 From bbf738a2c1052d9822fc69d4dd660190752e63b8 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Tue, 14 Aug 2018 15:45:00 -0400 Subject: more comments changes --- googlemock/src/gmock-spec-builders.cc | 2 +- googlemock/src/gmock.cc | 2 +- googletest/test/googletest-options-test.cc | 2 +- googletest/test/gtest_repeat_test.cc | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc index 83cc9cc..dc6f5ac 100644 --- a/googlemock/src/gmock-spec-builders.cc +++ b/googlemock/src/gmock-spec-builders.cc @@ -606,7 +606,7 @@ class MockObjectRegistry { if (it->second.leakable) // The user said it's fine to leak this object. continue; - // TODO(wan@google.com): Print the type of the leaked object. + // FIXME: Print the type of the leaked object. // This can help the user identify the leaked object. std::cout << "\n"; const MockObjectState& state = it->second; diff --git a/googlemock/src/gmock.cc b/googlemock/src/gmock.cc index 1cebede..36356c9 100644 --- a/googlemock/src/gmock.cc +++ b/googlemock/src/gmock.cc @@ -33,7 +33,7 @@ namespace testing { -// TODO(wan@google.com): support using environment variables to +// FIXME: support using environment variables to // control the flag values, like what Google Test does. GMOCK_DEFINE_bool_(catch_leaked_mocks, true, diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc index bbda04f..2a8dcda 100644 --- a/googletest/test/googletest-options-test.cc +++ b/googletest/test/googletest-options-test.cc @@ -106,7 +106,7 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { const bool success = exe_str == "app"; #else // FIXME: remove the hard-coded "lt-" prefix when - // Chandler Carruth's libtool replacement is ready. + // libtool replacement is ready. const bool success = exe_str == "googletest-options-test" || exe_str == "gtest_all_test" || diff --git a/googletest/test/gtest_repeat_test.cc b/googletest/test/gtest_repeat_test.cc index 204a091..50876c7 100644 --- a/googletest/test/gtest_repeat_test.cc +++ b/googletest/test/gtest_repeat_test.cc @@ -118,7 +118,7 @@ class MyParamTest : public testing::TestWithParam {}; TEST_P(MyParamTest, ShouldPass) { // FIXME: Make parameter value checking robust - // WRT order of tests. + // WRT order of tests. GTEST_CHECK_INT_EQ_(g_param_test_count % kNumberOfParamTests, GetParam()); g_param_test_count++; } -- cgit v0.12 From f0e4c411ca08f01068162483e92810001b178a60 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Tue, 14 Aug 2018 16:05:55 -0400 Subject: more comments changes --- googlemock/src/gmock-spec-builders.cc | 2 +- googletest/test/googletest-options-test.cc | 3 +-- googletest/test/gtest_repeat_test.cc | 3 +-- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc index dc6f5ac..b93f4e0 100644 --- a/googlemock/src/gmock-spec-builders.cc +++ b/googlemock/src/gmock-spec-builders.cc @@ -782,7 +782,7 @@ void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, const TestInfo* const test_info = UnitTest::GetInstance()->current_test_info(); if (test_info != NULL) { - // TODO(wan@google.com): record the test case name when the + // FIXME: record the test case name when the // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or // TearDownTestCase(). state.first_used_test_case = test_info->test_case_name(); diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc index 2a8dcda..edd4eba 100644 --- a/googletest/test/googletest-options-test.cc +++ b/googletest/test/googletest-options-test.cc @@ -105,8 +105,7 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { #elif GTEST_OS_FUCHSIA const bool success = exe_str == "app"; #else - // FIXME: remove the hard-coded "lt-" prefix when - // libtool replacement is ready. + // FIXME: remove the hard-coded "lt-" prefix when libtool replacement is ready const bool success = exe_str == "googletest-options-test" || exe_str == "gtest_all_test" || diff --git a/googletest/test/gtest_repeat_test.cc b/googletest/test/gtest_repeat_test.cc index 50876c7..1e8f499 100644 --- a/googletest/test/gtest_repeat_test.cc +++ b/googletest/test/gtest_repeat_test.cc @@ -117,8 +117,7 @@ const int kNumberOfParamTests = 10; class MyParamTest : public testing::TestWithParam {}; TEST_P(MyParamTest, ShouldPass) { - // FIXME: Make parameter value checking robust - // WRT order of tests. + // FIXME: Make parameter value checking robust WRT order of tests. GTEST_CHECK_INT_EQ_(g_param_test_count % kNumberOfParamTests, GetParam()); g_param_test_count++; } -- cgit v0.12 From ca87cc72e222a2b2ffcfac686801946451e09ef1 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Wed, 15 Aug 2018 16:38:42 -0400 Subject: googletest export - 208874130 Copybara tweaks, testing various round-trip sutuations(fu... by misterg - 208880646 Fix header guards and remove special case copybara by misterg - 208874252 Copybara tweaks for googletest reversible transform by misterg - 208853103 Adding a flow to export PR from GitHub into Google3 and a... by misterg - 208708150 Removing leakr-sensitive words. by misterg - 208672083 Import of OSS PR 1665 by misterg - 208663904 Remove LEAKR "author" warnings for googletest copybara ex... by misterg - 208646244 Incrementally finalizing OSS<->google3 transforms by misterg - 208548323 Move custom google3 only code to custom/ by misterg - 208234974 Removed scrubs, replaced with reversible transforms by misterg - 208211213 Move custom tests under custom by misterg - 208082996 Replace of OSS insert with reversible replace by misterg - 208072299 Replace scrubs with reversible replaces, incrementally ge... by misterg - 208059357 Replace scrub with reversible replace by misterg - 208055415 Fixing GCC brace warning that shows up in OSS with GCC8 a... by misterg - 207933728 Incrementally getting close to the reversible transformat... by misterg - 207917581 Removing stripping with replace dictionary entries to eas... by misterg - 207911026 Incremental Tweaks, on the way to reversible google3<-> g... by misterg - 207905179 Removing unnecessary comments stripping by misterg - 207901741 Fix typo in Fuchsia death-test implementation. by Abseil Team - 207776408 Move custom tests into /custom by misterg - 207746583 Remove stripping for printer for absl:variant by misterg - 207733597 Suppress default exception handling for death-test proces... by Abseil Team - 207719598 Import of googletest from Github. by misterg - 207283991 PR1673, extra parentheses in declaration cause GCC 8.1.1 ... by misterg - 206986279 Fix Duplicate definition, (original in googletest-test_te... by misterg - 206980794 Allow googletest-json-output unitest to handle supporting... by misterg - 206957064 Refactor to avoid OSS round-trip transformation problems ... by misterg - 206760733 Fixed weird syntax in these tests that was causing OSS tr... by misterg - 206750694 Tweak copybara, by misterg - 206611945 Make files consistent to enable copybara round-trip trans... by misterg - 206589404 OSS changes to open source two more tests by misterg - 206355044 Fixing copybara (was missing comment) by misterg - 206323492 Make reversible transforms possible for Copybara OSS<->go... by misterg - 206011852 Consolidate various copybara files into one file. by misterg - 205999518 remove weird char, should be space. pump and generated .h... by misterg - 205897244 Small cleanups to avoid potentially hard-to-reverse OSS t... by misterg - 205894405 Simplifying include path for tests. by misterg - 205892873 Removing obsolete files by misterg - 205873647 Simplifying include path for samples. by misterg - 205712910 Continue restructuring, will have common copybara file to... by misterg - 205711819 Removing non-ASCII chars by misterg - 205702635 Refactor internal googletest name to match OSS Name by misterg - 205403311 Comments change by misterg - 205246538 OSS community (https://github.com/google/googletest/pull/... by misterg - 205242422 Moving RE2 into custom where it rightfully belongs by misterg - 205138666 Add a 3-ary Property() matcher overload for ref-qualified... by Abseil Team - 205128154 Automated g4 rollback of changelist 205108639. by misterg - 205108639 Moving RE2 into custom where it rightfully belongs by misterg - 205102342 Comment link fix by misterg - 205097052 OSS sync, still need to worry about not C++11 by misterg - 205080271 Keeping up with the changes, ensure that the code still t... by misterg - 204815384 Mark the various RE legacy versions of the matchers as de... by Abseil Team - 204744294 OSS, someone noticed that if GTEST_HAS_EXCEPTIONS is set ... by misterg - 204363541 Add stacktrace support to the non-Google3 version of Goog... by Abseil Team - 204330832 Google Test: absl::variant is now open source, so add the by Abseil Team - 204130690 Bringing in OSS PR 1647 by misterg - 203979061 Set 'reason' field for leakr.disable_check() transformati... by Abseil Team - 203954557 Fixing comments, otherwise copybara leaves extra "//" in ... by misterg - 203487065 Correctly handle legacy regular expressions in googletest... by Abseil Team - 201997367 Remove references to GTEST_HAS_PROTOBUF_. by Abseil Team - 201735597 Upgrade gUnit from RE to RE2 -- Step 3/4 by Abseil Team - 201229160 Upgrade gUnit from RE to RE2 -- Step 1/4 by Abseil Team - 201228020 Remove extra copy of gunit samples - there should really ... by misterg - 200602156 Eliminate GTEST_TEST_FILTER_ENV_VAR_. by Abseil Team - 200500026 Make RegisterTasks faster by Abseil Team - 200361990 Add IWYU pragmas to gmock headers. by Abseil Team - 200292286 Fix speling by Abseil Team - 200222319 Adding docs to copybara. by misterg - 199815917 Fuchsia: Change fdio include path. by Abseil Team - 199195290 Remove launchpad dependency from Fuchsia. by Abseil Team - 199134849 Add printer for std::nullptr_t. by Abseil Team - 198710999 Properly decay variadic matchers by Abseil Team - 197733704 WIP - copybara script capable of google3-to-github by misterg - 197166689 Keeping up, sync cl/197012432 to combined "googletest" di... by misterg - 196253300 Keep up with changes,cl/196162435 by misterg - 195816901 go/googletest-plan by misterg - 195816542 Moving http://cl/167016557 and http://cl/195690905 into c... by misterg - 195712930 Following up for http://cl/195677772 More fixing typos, p... by misterg - 195702162 Moving http://cl/195020996 into combined dir by misterg - 195677772 Fix typos, the original IWYU was by misterg - 195249681 go/googletest-plan , Combine gUnit and gMock into third_p... by misterg PiperOrigin-RevId: 208874130 --- googlemock/include/gmock/gmock-more-matchers.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/googlemock/include/gmock/gmock-more-matchers.h b/googlemock/include/gmock/gmock-more-matchers.h index e5460e7..1c9a399 100644 --- a/googlemock/include/gmock/gmock-more-matchers.h +++ b/googlemock/include/gmock/gmock-more-matchers.h @@ -37,8 +37,8 @@ // GOOGLETEST_CM0002 DO NOT DELETE -#ifndef GMOCK_GMOCK_MORE_MATCHERS_H_ -#define GMOCK_GMOCK_MORE_MATCHERS_H_ +#ifndef GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_ +#define GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_ #include "gmock/gmock-generated-matchers.h" @@ -89,4 +89,4 @@ MATCHER(IsFalse, negation ? "is true" : "is false") { } // namespace testing -#endif // GMOCK_GMOCK_MORE_MATCHERS_H_ +#endif // GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_ -- cgit v0.12 From c38f4b9f2c542d16611b59e37b5e4d2ec0c8f924 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 16 Aug 2018 13:18:13 -0400 Subject: Small style changes. Just small style changes and we can accept this PR --- googletest/src/gtest-port.cc | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index f6bc125..fecb5d1 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -296,8 +296,8 @@ void Mutex::AssertHeld() { namespace { -// Use the RAII idiom to flag mem allocs that are intentionally never -// deallocated. The motivation is to silence the false positive mem leaks +// Use the RAII idiom to flag mem allocs that are intentionally never +// deallocated. The motivation is to silence the false positive mem leaks // that are reported by the debug version of MS's CRT which can only detect // if an alloc is missing a matching deallocation. // Example: @@ -306,24 +306,24 @@ namespace { // class MemoryIsNotDeallocated { -public: + public: MemoryIsNotDeallocated() : old_crtdbg_flag_(0) { #ifdef _MSC_VER old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT // doesn't report mem leak if there's no matching deallocation. _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF); -#endif // _MSC_VER +#endif // _MSC_VER } ~MemoryIsNotDeallocated() { #ifdef _MSC_VER // Restore the original _CRTDBG_ALLOC_MEM_DF flag _CrtSetDbgFlag(old_crtdbg_flag_); -#endif // _MSC_VER +#endif // _MSC_VER } -private: + private: int old_crtdbg_flag_; GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated); @@ -584,17 +584,11 @@ class ThreadLocalRegistryImpl { return 0; } - // Return a newly constructed ThreadIdToThreadLocals that's intentionally never deleted - static ThreadIdToThreadLocals* NewThreadIdToThreadLocals() { - // Use RAII to flag that following mem alloc is never deallocated. - MemoryIsNotDeallocated memory_is_not_deallocated; - return new ThreadIdToThreadLocals; - } - // Returns map of thread local instances. static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() { mutex_.AssertHeld(); - static ThreadIdToThreadLocals* map = NewThreadIdToThreadLocals(); + MemoryIsNotDeallocated memory_is_not_deallocated; + static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals(); return map; } -- cgit v0.12 From b1bfdf0bf48bb2288ba73bc8f423de2831e0032f Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 16 Aug 2018 15:10:07 -0400 Subject: Small formatting change And then we can merge --- googletest/include/gtest/internal/gtest-port.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 1d5b24b..786497d 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -2107,8 +2107,8 @@ class MutexBase { // particular, the owner_ field (a pthread_t) is not explicitly initialized. // This allows initialization to work whether pthread_t is a scalar or struct. // The flag -Wmissing-field-initializers must not be specified for this to work. -# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ - ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false, 0 } +#define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ + ::testing::internal::MutexBase mutex = {PTHREAD_MUTEX_INITIALIZER, false, 0} // The Mutex class can only be used for mutexes created at runtime. It // shares its API with MutexBase otherwise. -- cgit v0.12 -- cgit v0.12