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 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 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 From 079641531492b0f5b87e08278aa229d047bea1e5 Mon Sep 17 00:00:00 2001 From: Vadim Berezniker Date: Fri, 17 Aug 2018 10:49:10 -0700 Subject: std references shouldn't be fully qualified --- googletest/docs/advanced.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index 0a92e52..3a097f1 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -572,7 +572,7 @@ namespace foo { 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) { + friend std::ostream& operator<<(std::ostream& os, const Bar& bar) { return os << bar.DebugString(); // whatever needed to print bar to os } }; @@ -580,7 +580,7 @@ class Bar { // We want googletest to be able to print instances of this. // 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) { +std::ostream& operator<<(std::ostream& os, const Bar& bar) { return os << bar.DebugString(); // whatever needed to print bar to os } @@ -601,7 +601,7 @@ namespace foo { class Bar { ... - friend void PrintTo(const Bar& bar, ::std::ostream* os) { + friend void PrintTo(const Bar& bar, std::ostream* os) { *os << bar.DebugString(); // whatever needed to print bar to os } }; @@ -609,7 +609,7 @@ class Bar { // 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) { +void PrintTo(const Bar& bar, std::ostream* os) { *os << bar.DebugString(); // whatever needed to print bar to os } -- cgit v0.12