summaryrefslogtreecommitdiffstats
path: root/googletest
diff options
context:
space:
mode:
Diffstat (limited to 'googletest')
-rw-r--r--googletest/CMakeLists.txt16
-rw-r--r--googletest/README.md36
-rw-r--r--googletest/cmake/internal_utils.cmake23
-rw-r--r--googletest/include/gtest/gtest-assertion-result.h4
-rw-r--r--googletest/include/gtest/gtest-death-test.h6
-rw-r--r--googletest/include/gtest/gtest-matchers.h65
-rw-r--r--googletest/include/gtest/gtest-message.h2
-rw-r--r--googletest/include/gtest/gtest-param-test.h48
-rw-r--r--googletest/include/gtest/gtest-printers.h102
-rw-r--r--googletest/include/gtest/gtest-spi.h2
-rw-r--r--googletest/include/gtest/gtest-test-part.h2
-rw-r--r--googletest/include/gtest/gtest-typed-test.h34
-rw-r--r--googletest/include/gtest/gtest.h95
-rw-r--r--googletest/include/gtest/internal/gtest-death-test-internal.h7
-rw-r--r--googletest/include/gtest/internal/gtest-filepath.h17
-rw-r--r--googletest/include/gtest/internal/gtest-internal.h21
-rw-r--r--googletest/include/gtest/internal/gtest-param-util.h84
-rw-r--r--googletest/include/gtest/internal/gtest-port-arch.h2
-rw-r--r--googletest/include/gtest/internal/gtest-port.h453
-rw-r--r--googletest/include/gtest/internal/gtest-string.h3
-rw-r--r--googletest/include/gtest/internal/gtest-type-util.h4
-rw-r--r--googletest/samples/prime_tables.h5
-rw-r--r--googletest/samples/sample10_unittest.cc1
-rw-r--r--googletest/samples/sample9_unittest.cc1
-rw-r--r--googletest/src/gtest-assertion-result.cc4
-rw-r--r--googletest/src/gtest-death-test.cc154
-rw-r--r--googletest/src/gtest-filepath.cc114
-rw-r--r--googletest/src/gtest-internal-inl.h26
-rw-r--r--googletest/src/gtest-port.cc102
-rw-r--r--googletest/src/gtest-printers.cc2
-rw-r--r--googletest/src/gtest-test-part.cc2
-rw-r--r--googletest/src/gtest-typed-test.cc2
-rw-r--r--googletest/src/gtest.cc317
-rw-r--r--googletest/src/gtest_main.cc18
-rwxr-xr-xgoogletest/test/googletest-break-on-failure-unittest.py77
-rw-r--r--googletest/test/googletest-break-on-failure-unittest_.cc8
-rwxr-xr-xgoogletest/test/googletest-catch-exceptions-test.py247
-rwxr-xr-xgoogletest/test/googletest-color-test.py68
-rw-r--r--googletest/test/googletest-death-test-test.cc49
-rw-r--r--googletest/test/googletest-death-test_ex_test.cc2
-rwxr-xr-xgoogletest/test/googletest-env-var-test.py2
-rwxr-xr-xgoogletest/test/googletest-failfast-unittest.py201
-rw-r--r--googletest/test/googletest-filepath-test.cc42
-rwxr-xr-xgoogletest/test/googletest-filter-unittest.py416
-rw-r--r--googletest/test/googletest-global-environment-unittest.py89
-rw-r--r--googletest/test/googletest-json-outfiles-test.py165
-rw-r--r--googletest/test/googletest-json-output-unittest.py1334
-rwxr-xr-xgoogletest/test/googletest-list-tests-unittest.py100
-rw-r--r--googletest/test/googletest-listener-test.cc8
-rw-r--r--googletest/test/googletest-message-test.cc3
-rw-r--r--googletest/test/googletest-options-test.cc26
-rwxr-xr-xgoogletest/test/googletest-output-test.py173
-rw-r--r--googletest/test/googletest-output-test_.cc18
-rw-r--r--googletest/test/googletest-param-test-invalid-name1-test.py2
-rw-r--r--googletest/test/googletest-param-test-invalid-name2-test.py3
-rw-r--r--googletest/test/googletest-param-test-test.cc80
-rw-r--r--googletest/test/googletest-port-test.cc43
-rw-r--r--googletest/test/googletest-printers-test.cc52
-rwxr-xr-xgoogletest/test/googletest-setuptestsuite-test.py16
-rwxr-xr-xgoogletest/test/googletest-shuffle-test.py201
-rw-r--r--googletest/test/googletest-shuffle-test_.cc1
-rwxr-xr-xgoogletest/test/googletest-throw-on-failure-test.py68
-rwxr-xr-xgoogletest/test/googletest-uninitialized-test.py7
-rw-r--r--googletest/test/gtest-typed-test_test.cc5
-rw-r--r--googletest/test/gtest_dirs_test.cc101
-rwxr-xr-xgoogletest/test/gtest_help_test.py65
-rw-r--r--googletest/test/gtest_help_test_.cc2
-rw-r--r--googletest/test/gtest_json_test_utils.py2
-rw-r--r--googletest/test/gtest_list_output_unittest.py27
-rw-r--r--googletest/test/gtest_pred_impl_unittest.cc1
-rwxr-xr-xgoogletest/test/gtest_skip_check_output_test.py3
-rwxr-xr-xgoogletest/test/gtest_skip_environment_check_output_test.py3
-rw-r--r--googletest/test/gtest_stress_test.cc7
-rwxr-xr-xgoogletest/test/gtest_test_utils.py47
-rwxr-xr-xgoogletest/test/gtest_testbridge_test.py2
-rw-r--r--googletest/test/gtest_unittest.cc87
-rw-r--r--googletest/test/gtest_xml_outfile2_test_.cc36
-rwxr-xr-xgoogletest/test/gtest_xml_outfiles_test.py38
-rwxr-xr-xgoogletest/test/gtest_xml_output_unittest.py200
-rwxr-xr-xgoogletest/test/gtest_xml_test_utils.py153
80 files changed, 3552 insertions, 2502 deletions
diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt
index aa00a5f..95bfa44 100644
--- a/googletest/CMakeLists.txt
+++ b/googletest/CMakeLists.txt
@@ -125,6 +125,22 @@ include_directories(${gtest_build_include_dirs})
# aggressive about warnings.
cxx_library(gtest "${cxx_strict}" src/gtest-all.cc)
set_target_properties(gtest PROPERTIES VERSION ${GOOGLETEST_VERSION})
+if(GTEST_HAS_ABSL)
+ target_compile_definitions(gtest PUBLIC GTEST_HAS_ABSL=1)
+ target_link_libraries(gtest PUBLIC
+ absl::failure_signal_handler
+ absl::stacktrace
+ absl::symbolize
+ absl::flags_parse
+ absl::flags_reflection
+ absl::flags_usage
+ absl::strings
+ absl::any
+ absl::optional
+ absl::variant
+ re2::re2
+ )
+endif()
cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc)
set_target_properties(gtest_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
# If the CMake version supports it, attach header directory information
diff --git a/googletest/README.md b/googletest/README.md
index 75b3d52..995834e 100644
--- a/googletest/README.md
+++ b/googletest/README.md
@@ -25,7 +25,7 @@ When building GoogleTest as a standalone project, the typical workflow starts
with
```
-git clone https://github.com/google/googletest.git -b release-1.12.0
+git clone https://github.com/google/googletest.git -b v1.13.0
cd googletest # Main directory of the cloned repository.
mkdir build # Create a directory to hold the build output.
cd build
@@ -152,11 +152,15 @@ GoogleTest is thread-safe where the pthread library is available. After
If GoogleTest doesn't correctly detect whether pthread is available in your
environment, you can force it with
- -DGTEST_HAS_PTHREAD=1
+```
+-DGTEST_HAS_PTHREAD=1
+```
or
- -DGTEST_HAS_PTHREAD=0
+```
+-DGTEST_HAS_PTHREAD=0
+```
When GoogleTest uses pthread, you may need to add flags to your compiler and/or
linker to select the pthread library, or you'll get link errors. If you use the
@@ -172,23 +176,27 @@ as a DLL on Windows) if you prefer.
To compile *gtest* as a shared library, add
- -DGTEST_CREATE_SHARED_LIBRARY=1
+```
+-DGTEST_CREATE_SHARED_LIBRARY=1
+```
to the compiler flags. You'll also need to tell the linker to produce a shared
library instead - consult your linker's manual for how to do it.
To compile your *tests* that use the gtest shared library, add
- -DGTEST_LINKED_AS_SHARED_LIBRARY=1
+```
+-DGTEST_LINKED_AS_SHARED_LIBRARY=1
+```
to the compiler flags.
Note: while the above steps aren't technically necessary today when using some
compilers (e.g. GCC), they may become necessary in the future, if we decide to
improve the speed of loading the library (see
-<http://gcc.gnu.org/wiki/Visibility> for details). Therefore you are recommended
-to always add the above flags when using GoogleTest as a shared library.
-Otherwise a future release of GoogleTest may break your build script.
+<https://gcc.gnu.org/wiki/Visibility> for details). Therefore you are
+recommended to always add the above flags when using GoogleTest as a shared
+library. Otherwise a future release of GoogleTest may break your build script.
### Avoiding Macro Name Clashes
@@ -200,7 +208,9 @@ rename its macro to avoid the conflict.
Specifically, if both GoogleTest and some other code define macro FOO, you can
add
- -DGTEST_DONT_DEFINE_FOO=1
+```
+-DGTEST_DONT_DEFINE_FOO=1
+```
to the compiler flags to tell GoogleTest to change the macro's name from `FOO`
to `GTEST_FOO`. Currently `FOO` can be `ASSERT_EQ`, `ASSERT_FALSE`, `ASSERT_GE`,
@@ -208,10 +218,14 @@ to `GTEST_FOO`. Currently `FOO` can be `ASSERT_EQ`, `ASSERT_FALSE`, `ASSERT_GE`,
`EXPECT_FALSE`, `EXPECT_TRUE`, `FAIL`, `SUCCEED`, `TEST`, or `TEST_F`. For
example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write
- GTEST_TEST(SomeTest, DoesThis) { ... }
+```
+GTEST_TEST(SomeTest, DoesThis) { ... }
+```
instead of
- TEST(SomeTest, DoesThis) { ... }
+```
+TEST(SomeTest, DoesThis) { ... }
+```
in order to define a test.
diff --git a/googletest/cmake/internal_utils.cmake b/googletest/cmake/internal_utils.cmake
index 6f7fdc2..fa7da4e 100644
--- a/googletest/cmake/internal_utils.cmake
+++ b/googletest/cmake/internal_utils.cmake
@@ -16,13 +16,18 @@ if (POLICY CMP0054)
cmake_policy(SET CMP0054 NEW)
endif (POLICY CMP0054)
+if (POLICY CMP0069)
+ cmake_policy(SET CMP0069 NEW)
+endif (POLICY CMP0069)
+
# Tweaks CMake's default compiler/linker settings to suit Google Test's needs.
#
# This must be a macro(), as inside a function string() can only
# update variables in the function scope.
macro(fix_default_compiler_settings_)
- if (MSVC)
- # For MSVC, CMake sets certain flags to defaults we want to override.
+ if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC|Clang")
+ # For MSVC and Clang, CMake sets certain flags to defaults we want to
+ # override.
# This replacement code is taken from sample in the CMake Wiki at
# https://gitlab.kitware.com/cmake/community/wikis/FAQ#dynamic-replace.
foreach (flag_var
@@ -39,6 +44,10 @@ macro(fix_default_compiler_settings_)
# on CRT DLLs being available. CMake always defaults to using shared
# CRT libraries, so we override that default here.
string(REPLACE "/MD" "-MT" ${flag_var} "${${flag_var}}")
+
+ # When using Ninja with Clang, static builds pass -D_DLL on Windows.
+ # This is incorrect and should not happen, so we fix that here.
+ string(REPLACE "-D_DLL" "" ${flag_var} "${${flag_var}}")
endif()
# We prefer more strict warning checking for building Google Test.
@@ -86,13 +95,13 @@ macro(config_compiler_and_linker)
set(cxx_base_flags "${cxx_base_flags} -utf-8")
endif()
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
- set(cxx_base_flags "-Wall -Wshadow -Wconversion")
+ set(cxx_base_flags "-Wall -Wshadow -Wconversion -Wundef")
set(cxx_exception_flags "-fexceptions")
set(cxx_no_exception_flags "-fno-exceptions")
set(cxx_strict_flags "-W -Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch -Wunused-parameter -Wcast-align -Wchar-subscripts -Winline -Wredundant-decls")
set(cxx_no_rtti_flags "-fno-rtti")
elseif (CMAKE_COMPILER_IS_GNUCXX)
- set(cxx_base_flags "-Wall -Wshadow")
+ set(cxx_base_flags "-Wall -Wshadow -Wundef")
if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0.0)
set(cxx_base_flags "${cxx_base_flags} -Wno-error=dangling-else")
endif()
@@ -254,10 +263,12 @@ endif()
# Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE.
if ("${CMAKE_VERSION}" VERSION_LESS "3.12.0")
find_package(PythonInterp)
+ set(PYTHONINTERP_FOUND ${PYTHONINTERP_FOUND} CACHE INTERNAL "")
+ set(PYTHON_EXECUTABLE ${PYTHON_EXECUTABLE} CACHE INTERNAL "")
else()
find_package(Python COMPONENTS Interpreter)
- set(PYTHONINTERP_FOUND ${Python_Interpreter_FOUND})
- set(PYTHON_EXECUTABLE ${Python_EXECUTABLE})
+ set(PYTHONINTERP_FOUND ${Python_Interpreter_FOUND} CACHE INTERNAL "")
+ set(PYTHON_EXECUTABLE ${Python_EXECUTABLE} CACHE INTERNAL "")
endif()
# cxx_test_with_flags(name cxx_flags libs srcs...)
diff --git a/googletest/include/gtest/gtest-assertion-result.h b/googletest/include/gtest/gtest-assertion-result.h
index addbb59..62fbea6 100644
--- a/googletest/include/gtest/gtest-assertion-result.h
+++ b/googletest/include/gtest/gtest-assertion-result.h
@@ -181,7 +181,7 @@ class GTEST_API_ AssertionResult {
// assertion's expectation). When nothing has been streamed into the
// object, returns an empty string.
const char* message() const {
- return message_.get() != nullptr ? message_->c_str() : "";
+ return message_ != nullptr ? message_->c_str() : "";
}
// Deprecated; please use message() instead.
const char* failure_message() const { return message(); }
@@ -204,7 +204,7 @@ class GTEST_API_ AssertionResult {
private:
// Appends the contents of message to message_.
void AppendMessage(const Message& a_message) {
- if (message_.get() == nullptr) message_.reset(new ::std::string);
+ if (message_ == nullptr) message_.reset(new ::std::string);
message_->append(a_message.GetString().c_str());
}
diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h
index 84e5a5b..08fef8c 100644
--- a/googletest/include/gtest/gtest-death-test.h
+++ b/googletest/include/gtest/gtest-death-test.h
@@ -51,7 +51,7 @@ GTEST_DECLARE_string_(death_test_style);
namespace testing {
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
namespace internal {
@@ -203,7 +203,7 @@ class GTEST_API_ ExitedWithCode {
const int exit_code_;
};
-#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
+#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)
// Tests that an exit code describes an exit due to termination by a
// given signal.
class GTEST_API_ KilledBySignal {
@@ -328,7 +328,7 @@ class GTEST_API_ KilledBySignal {
// death tests are supported; otherwise they just issue a warning. This is
// useful when you are combining death test assertions with normal test
// assertions in one test.
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
EXPECT_DEATH(statement, regex)
#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
diff --git a/googletest/include/gtest/gtest-matchers.h b/googletest/include/gtest/gtest-matchers.h
index 4a60b0d..d73d834 100644
--- a/googletest/include/gtest/gtest-matchers.h
+++ b/googletest/include/gtest/gtest-matchers.h
@@ -40,6 +40,7 @@
#define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
#include <atomic>
+#include <functional>
#include <memory>
#include <ostream>
#include <string>
@@ -178,43 +179,6 @@ class MatcherInterface : public MatcherDescriberInterface {
namespace internal {
-struct AnyEq {
- template <typename A, typename B>
- bool operator()(const A& a, const B& b) const {
- return a == b;
- }
-};
-struct AnyNe {
- template <typename A, typename B>
- bool operator()(const A& a, const B& b) const {
- return a != b;
- }
-};
-struct AnyLt {
- template <typename A, typename B>
- bool operator()(const A& a, const B& b) const {
- return a < b;
- }
-};
-struct AnyGt {
- template <typename A, typename B>
- bool operator()(const A& a, const B& b) const {
- return a > b;
- }
-};
-struct AnyLe {
- template <typename A, typename B>
- bool operator()(const A& a, const B& b) const {
- return a <= b;
- }
-};
-struct AnyGe {
- template <typename A, typename B>
- bool operator()(const A& a, const B& b) const {
- return a >= b;
- }
-};
-
// A match result listener that ignores the explanation.
class DummyMatchResultListener : public MatchResultListener {
public:
@@ -758,50 +722,53 @@ class ComparisonBase {
};
template <typename Rhs>
-class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
+class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, std::equal_to<>> {
public:
explicit EqMatcher(const Rhs& rhs)
- : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) {}
+ : ComparisonBase<EqMatcher<Rhs>, Rhs, std::equal_to<>>(rhs) {}
static const char* Desc() { return "is equal to"; }
static const char* NegatedDesc() { return "isn't equal to"; }
};
template <typename Rhs>
-class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
+class NeMatcher
+ : public ComparisonBase<NeMatcher<Rhs>, Rhs, std::not_equal_to<>> {
public:
explicit NeMatcher(const Rhs& rhs)
- : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) {}
+ : ComparisonBase<NeMatcher<Rhs>, Rhs, std::not_equal_to<>>(rhs) {}
static const char* Desc() { return "isn't equal to"; }
static const char* NegatedDesc() { return "is equal to"; }
};
template <typename Rhs>
-class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
+class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, std::less<>> {
public:
explicit LtMatcher(const Rhs& rhs)
- : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) {}
+ : ComparisonBase<LtMatcher<Rhs>, Rhs, std::less<>>(rhs) {}
static const char* Desc() { return "is <"; }
static const char* NegatedDesc() { return "isn't <"; }
};
template <typename Rhs>
-class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
+class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, std::greater<>> {
public:
explicit GtMatcher(const Rhs& rhs)
- : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) {}
+ : ComparisonBase<GtMatcher<Rhs>, Rhs, std::greater<>>(rhs) {}
static const char* Desc() { return "is >"; }
static const char* NegatedDesc() { return "isn't >"; }
};
template <typename Rhs>
-class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
+class LeMatcher
+ : public ComparisonBase<LeMatcher<Rhs>, Rhs, std::less_equal<>> {
public:
explicit LeMatcher(const Rhs& rhs)
- : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) {}
+ : ComparisonBase<LeMatcher<Rhs>, Rhs, std::less_equal<>>(rhs) {}
static const char* Desc() { return "is <="; }
static const char* NegatedDesc() { return "isn't <="; }
};
template <typename Rhs>
-class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
+class GeMatcher
+ : public ComparisonBase<GeMatcher<Rhs>, Rhs, std::greater_equal<>> {
public:
explicit GeMatcher(const Rhs& rhs)
- : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) {}
+ : ComparisonBase<GeMatcher<Rhs>, Rhs, std::greater_equal<>>(rhs) {}
static const char* Desc() { return "is >="; }
static const char* NegatedDesc() { return "isn't >="; }
};
diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h
index 6c8bf90..4d4b152 100644
--- a/googletest/include/gtest/gtest-message.h
+++ b/googletest/include/gtest/gtest-message.h
@@ -50,7 +50,9 @@
#include <limits>
#include <memory>
+#include <ostream>
#include <sstream>
+#include <string>
#include "gtest/internal/gtest-port.h"
diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h
index b55119a..49a47ea 100644
--- a/googletest/include/gtest/gtest-param-test.h
+++ b/googletest/include/gtest/gtest-param-test.h
@@ -407,9 +407,50 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
return internal::CartesianProductHolder<Generator...>(g...);
}
+// ConvertGenerator() wraps a parameter generator in order to cast each produced
+// value through a known type before supplying it to the test suite
+//
+// Synopsis:
+// ConvertGenerator<T>(gen)
+// - returns a generator producing the same elements as generated by gen, but
+// each element is static_cast to type T before being returned
+//
+// It is useful when using the Combine() function to get the generated
+// parameters in a custom type instead of std::tuple
+//
+// Example:
+//
+// This will instantiate tests in test suite AnimalTest each one with
+// the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
+// tuple("dog", BLACK), and tuple("dog", WHITE):
+//
+// enum Color { BLACK, GRAY, WHITE };
+// struct ParamType {
+// using TupleT = std::tuple<const char*, Color>;
+// std::string animal;
+// Color color;
+// ParamType(TupleT t) : animal(std::get<0>(t)), color(std::get<1>(t)) {}
+// };
+// class AnimalTest
+// : public testing::TestWithParam<ParamType> {...};
+//
+// TEST_P(AnimalTest, AnimalLooksNice) {...}
+//
+// INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
+// ConvertGenerator<ParamType::TupleT>(
+// Combine(Values("cat", "dog"),
+// Values(BLACK, WHITE))));
+//
+template <typename T>
+internal::ParamConverterGenerator<T> ConvertGenerator(
+ internal::ParamGenerator<T> gen) {
+ return internal::ParamConverterGenerator<T>(gen);
+}
+
#define TEST_P(test_suite_name, test_name) \
class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
- : public test_suite_name { \
+ : public test_suite_name, \
+ private ::testing::internal::GTestNonCopyable { \
public: \
GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
void TestBody() override; \
@@ -429,11 +470,6 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
return 0; \
} \
static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
- GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
- (const GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &) = delete; \
- GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=( \
- const GTEST_TEST_CLASS_NAME_(test_suite_name, \
- test_name) &) = delete; /* NOLINT */ \
}; \
int GTEST_TEST_CLASS_NAME_(test_suite_name, \
test_name)::gtest_registering_dummy_ = \
diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h
index 19c3e0b..539d99c 100644
--- a/googletest/include/gtest/gtest-printers.h
+++ b/googletest/include/gtest/gtest-printers.h
@@ -108,6 +108,7 @@
#include <string>
#include <tuple>
#include <type_traits>
+#include <typeinfo>
#include <utility>
#include <vector>
@@ -210,8 +211,8 @@ struct StreamPrinter {
// ADL (possibly involving implicit conversions).
// (Use SFINAE via return type, because it seems GCC < 12 doesn't handle name
// lookup properly when we do it in the template parameter list.)
- static auto PrintValue(const T& value, ::std::ostream* os)
- -> decltype((void)(*os << value)) {
+ static auto PrintValue(const T& value, ::std::ostream* os)
+ -> decltype((void)(*os << value)) {
// Call streaming operator found by ADL, possibly with implicit conversions
// of the arguments.
*os << value;
@@ -306,9 +307,10 @@ template <typename T>
void PrintWithFallback(const T& value, ::std::ostream* os) {
using Printer = typename FindFirstPrinter<
T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
+ ProtobufPrinter,
internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
- ProtobufPrinter, ConvertibleToIntegerPrinter,
- ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type;
+ ConvertibleToIntegerPrinter, ConvertibleToStringViewPrinter,
+ RawBytesPrinter, FallbackPrinter>::type;
Printer::PrintValue(value, os);
}
@@ -485,6 +487,87 @@ GTEST_API_ void PrintTo(__uint128_t v, ::std::ostream* os);
GTEST_API_ void PrintTo(__int128_t v, ::std::ostream* os);
#endif // __SIZEOF_INT128__
+// The default resolution used to print floating-point values uses only
+// 6 digits, which can be confusing if a test compares two values whose
+// difference lies in the 7th digit. So we'd like to print out numbers
+// in full precision.
+// However if the value is something simple like 1.1, full will print a
+// long string like 1.100000001 due to floating-point numbers not using
+// a base of 10. This routiune returns an appropriate resolution for a
+// given floating-point number, that is, 6 if it will be accurate, or a
+// max_digits10 value (full precision) if it won't, for values between
+// 0.0001 and one million.
+// It does this by computing what those digits would be (by multiplying
+// by an appropriate power of 10), then dividing by that power again to
+// see if gets the original value back.
+// A similar algorithm applies for values larger than one million; note
+// that for those values, we must divide to get a six-digit number, and
+// then multiply to possibly get the original value again.
+template <typename FloatType>
+int AppropriateResolution(FloatType val) {
+ int full = std::numeric_limits<FloatType>::max_digits10;
+ if (val < 0) val = -val;
+
+ if (val < 1000000) {
+ FloatType mulfor6 = 1e10;
+ if (val >= 100000.0) { // 100,000 to 999,999
+ mulfor6 = 1.0;
+ } else if (val >= 10000.0) {
+ mulfor6 = 1e1;
+ } else if (val >= 1000.0) {
+ mulfor6 = 1e2;
+ } else if (val >= 100.0) {
+ mulfor6 = 1e3;
+ } else if (val >= 10.0) {
+ mulfor6 = 1e4;
+ } else if (val >= 1.0) {
+ mulfor6 = 1e5;
+ } else if (val >= 0.1) {
+ mulfor6 = 1e6;
+ } else if (val >= 0.01) {
+ mulfor6 = 1e7;
+ } else if (val >= 0.001) {
+ mulfor6 = 1e8;
+ } else if (val >= 0.0001) {
+ mulfor6 = 1e9;
+ }
+ if (static_cast<float>(static_cast<int32_t>(val * mulfor6 + 0.5)) /
+ mulfor6 ==
+ val)
+ return 6;
+ } else if (val < 1e10) {
+ FloatType divfor6 = 1.0;
+ if (val >= 1e9) { // 1,000,000,000 to 9,999,999,999
+ divfor6 = 10000;
+ } else if (val >= 1e8) { // 100,000,000 to 999,999,999
+ divfor6 = 1000;
+ } else if (val >= 1e7) { // 10,000,000 to 99,999,999
+ divfor6 = 100;
+ } else if (val >= 1e6) { // 1,000,000 to 9,999,999
+ divfor6 = 10;
+ }
+ if (static_cast<float>(static_cast<int32_t>(val / divfor6 + 0.5)) *
+ divfor6 ==
+ val)
+ return 6;
+ }
+ return full;
+}
+
+inline void PrintTo(float f, ::std::ostream* os) {
+ auto old_precision = os->precision();
+ os->precision(AppropriateResolution(f));
+ *os << f;
+ os->precision(old_precision);
+}
+
+inline void PrintTo(double d, ::std::ostream* os) {
+ auto old_precision = os->precision();
+ os->precision(AppropriateResolution(d));
+ *os << d;
+ os->precision(old_precision);
+}
+
// Overloads for C strings.
GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
inline void PrintTo(char* s, ::std::ostream* os) {
@@ -775,7 +858,7 @@ class UniversalPrinter<Variant<T...>> {
public:
static void Print(const Variant<T...>& value, ::std::ostream* os) {
*os << '(';
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
absl::visit(Visitor{os, value.index()}, value);
#else
std::visit(Visitor{os, value.index()}, value);
@@ -892,6 +975,13 @@ class UniversalTersePrinter<T&> {
UniversalPrint(value, os);
}
};
+template <typename T>
+class UniversalTersePrinter<std::reference_wrapper<T>> {
+ public:
+ static void Print(std::reference_wrapper<T> value, ::std::ostream* os) {
+ UniversalTersePrinter<T>::Print(value.get(), os);
+ }
+};
template <typename T, size_t N>
class UniversalTersePrinter<T[N]> {
public:
@@ -914,7 +1004,7 @@ template <>
class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
};
-#ifdef __cpp_char8_t
+#ifdef __cpp_lib_char8_t
template <>
class UniversalTersePrinter<const char8_t*> {
public:
diff --git a/googletest/include/gtest/gtest-spi.h b/googletest/include/gtest/gtest-spi.h
index bec8c48..c0613b6 100644
--- a/googletest/include/gtest/gtest-spi.h
+++ b/googletest/include/gtest/gtest-spi.h
@@ -33,6 +33,8 @@
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
#define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
+#include <string>
+
#include "gtest/gtest.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
diff --git a/googletest/include/gtest/gtest-test-part.h b/googletest/include/gtest/gtest-test-part.h
index 09cc8c3..8290b4d 100644
--- a/googletest/include/gtest/gtest-test-part.h
+++ b/googletest/include/gtest/gtest-test-part.h
@@ -35,6 +35,8 @@
#define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
#include <iosfwd>
+#include <ostream>
+#include <string>
#include <vector>
#include "gtest/internal/gtest-internal.h"
diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h
index bd35a32..72de536 100644
--- a/googletest/include/gtest/gtest-typed-test.h
+++ b/googletest/include/gtest/gtest-typed-test.h
@@ -267,28 +267,28 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
TYPED_TEST_SUITE_P
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
-#define TYPED_TEST_P(SuiteName, TestName) \
- namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
- template <typename gtest_TypeParam_> \
- class TestName : public SuiteName<gtest_TypeParam_> { \
- private: \
- typedef SuiteName<gtest_TypeParam_> TestFixture; \
- typedef gtest_TypeParam_ TypeParam; \
- void TestBody() override; \
- }; \
- static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
- GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
- __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
- GTEST_STRINGIFY_(TestName)); \
- } \
- template <typename gtest_TypeParam_> \
- void GTEST_SUITE_NAMESPACE_( \
+#define TYPED_TEST_P(SuiteName, TestName) \
+ namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
+ template <typename gtest_TypeParam_> \
+ class TestName : public SuiteName<gtest_TypeParam_> { \
+ private: \
+ typedef SuiteName<gtest_TypeParam_> TestFixture; \
+ typedef gtest_TypeParam_ TypeParam; \
+ void TestBody() override; \
+ }; \
+ static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
+ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
+ __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
+ GTEST_STRINGIFY_(TestName)); \
+ } \
+ template <typename gtest_TypeParam_> \
+ void GTEST_SUITE_NAMESPACE_( \
SuiteName)::TestName<gtest_TypeParam_>::TestBody()
// Note: this won't work correctly if the trailing arguments are macros.
#define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
- typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
+ typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
} \
static const char* const GTEST_REGISTERED_TEST_NAMES_( \
SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h
index d19a587..e543826 100644
--- a/googletest/include/gtest/gtest.h
+++ b/googletest/include/gtest/gtest.h
@@ -50,9 +50,14 @@
#define GOOGLETEST_INCLUDE_GTEST_GTEST_H_
#include <cstddef>
+#include <cstdint>
+#include <iomanip>
#include <limits>
#include <memory>
#include <ostream>
+#include <set>
+#include <sstream>
+#include <string>
#include <type_traits>
#include <vector>
@@ -161,11 +166,7 @@ namespace testing {
// Silence C4100 (unreferenced formal parameter) and 4805
// unsafe mix of type 'const int' and type 'const bool'
-#ifdef _MSC_VER
-#pragma warning(push)
-#pragma warning(disable : 4805)
-#pragma warning(disable : 4100)
-#endif
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4805 4100)
// The upper limit for valid stack trace depths.
const int kMaxStackTraceDepth = 100;
@@ -190,6 +191,17 @@ void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const std::string& message);
std::set<std::string>* GetIgnoredParameterizedTestSuites();
+// A base class that prevents subclasses from being copyable.
+// We do this instead of using '= delete' so as to avoid triggering warnings
+// inside user code regarding any of our declarations.
+class GTestNonCopyable {
+ public:
+ GTestNonCopyable() = default;
+ GTestNonCopyable(const GTestNonCopyable&) = delete;
+ GTestNonCopyable& operator=(const GTestNonCopyable&) = delete;
+ ~GTestNonCopyable() = default;
+};
+
} // namespace internal
// The friend relationship of some of these classes is cyclic.
@@ -285,7 +297,13 @@ class GTEST_API_ Test {
// SetUp/TearDown method of Environment objects registered with Google
// Test) will be output as attributes of the <testsuites> element.
static void RecordProperty(const std::string& key, const std::string& value);
- static void RecordProperty(const std::string& key, int value);
+ // We do not define a custom serialization except for values that can be
+ // converted to int64_t, but other values could be logged in this way.
+ template <typename T, std::enable_if_t<std::is_convertible<T, int64_t>::value,
+ bool> = true>
+ static void RecordProperty(const std::string& key, const T& value) {
+ RecordProperty(key, (Message() << value).GetString());
+ }
protected:
// Creates a Test object.
@@ -533,14 +551,14 @@ class GTEST_API_ TestInfo {
// Returns the name of the parameter type, or NULL if this is not a typed
// or a type-parameterized test.
const char* type_param() const {
- if (type_param_.get() != nullptr) return type_param_->c_str();
+ if (type_param_ != nullptr) return type_param_->c_str();
return nullptr;
}
// Returns the text representation of the value parameter, or NULL if this
// is not a value-parameterized test.
const char* value_param() const {
- if (value_param_.get() != nullptr) return value_param_->c_str();
+ if (value_param_ != nullptr) return value_param_->c_str();
return nullptr;
}
@@ -582,7 +600,7 @@ class GTEST_API_ TestInfo {
const TestResult* result() const { return &result_; }
private:
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
friend class internal::DefaultDeathTestFactory;
#endif // GTEST_HAS_DEATH_TEST
friend class Test;
@@ -679,7 +697,7 @@ class GTEST_API_ TestSuite {
// Returns the name of the parameter type, or NULL if this is not a
// type-parameterized test suite.
const char* type_param() const {
- if (type_param_.get() != nullptr) return type_param_->c_str();
+ if (type_param_ != nullptr) return type_param_->c_str();
return nullptr;
}
@@ -1625,7 +1643,7 @@ class GTEST_API_ AssertHelper {
// the GetParam() method.
//
// Use it with one of the parameter generator defining functions, like Range(),
-// Values(), ValuesIn(), Bool(), and Combine().
+// Values(), ValuesIn(), Bool(), Combine(), and ConvertGenerator<T>().
//
// class FooTest : public ::testing::TestWithParam<int> {
// protected:
@@ -1723,13 +1741,13 @@ class TestWithParam : public Test, public WithParamInterface<T> {};
#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
// Like GTEST_FAIL(), but at the given source file location.
-#define GTEST_FAIL_AT(file, line) \
- GTEST_MESSAGE_AT_(file, line, "Failed", \
- ::testing::TestPartResult::kFatalFailure)
+#define GTEST_FAIL_AT(file, line) \
+ return GTEST_MESSAGE_AT_(file, line, "Failed", \
+ ::testing::TestPartResult::kFatalFailure)
// Define this macro to 1 to omit the definition of FAIL(), which is a
// generic name and clashes with some other libraries.
-#if !GTEST_DONT_DEFINE_FAIL
+#if !(defined(GTEST_DONT_DEFINE_FAIL) && GTEST_DONT_DEFINE_FAIL)
#define FAIL() GTEST_FAIL()
#endif
@@ -1738,7 +1756,7 @@ class TestWithParam : public Test, public WithParamInterface<T> {};
// Define this macro to 1 to omit the definition of SUCCEED(), which
// is a generic name and clashes with some other libraries.
-#if !GTEST_DONT_DEFINE_SUCCEED
+#if !(defined(GTEST_DONT_DEFINE_SUCCEED) && GTEST_DONT_DEFINE_SUCCEED)
#define SUCCEED() GTEST_SUCCEED()
#endif
@@ -1782,19 +1800,19 @@ class TestWithParam : public Test, public WithParamInterface<T> {};
// Define these macros to 1 to omit the definition of the corresponding
// EXPECT or ASSERT, which clashes with some users' own code.
-#if !GTEST_DONT_DEFINE_EXPECT_TRUE
+#if !(defined(GTEST_DONT_DEFINE_EXPECT_TRUE) && GTEST_DONT_DEFINE_EXPECT_TRUE)
#define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)
#endif
-#if !GTEST_DONT_DEFINE_EXPECT_FALSE
+#if !(defined(GTEST_DONT_DEFINE_EXPECT_FALSE) && GTEST_DONT_DEFINE_EXPECT_FALSE)
#define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)
#endif
-#if !GTEST_DONT_DEFINE_ASSERT_TRUE
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_TRUE) && GTEST_DONT_DEFINE_ASSERT_TRUE)
#define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)
#endif
-#if !GTEST_DONT_DEFINE_ASSERT_FALSE
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_FALSE) && GTEST_DONT_DEFINE_ASSERT_FALSE)
#define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)
#endif
@@ -1873,27 +1891,27 @@ class TestWithParam : public Test, public WithParamInterface<T> {};
// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
// ASSERT_XY(), which clashes with some users' own code.
-#if !GTEST_DONT_DEFINE_ASSERT_EQ
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_EQ) && GTEST_DONT_DEFINE_ASSERT_EQ)
#define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
#endif
-#if !GTEST_DONT_DEFINE_ASSERT_NE
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_NE) && GTEST_DONT_DEFINE_ASSERT_NE)
#define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
#endif
-#if !GTEST_DONT_DEFINE_ASSERT_LE
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_LE) && GTEST_DONT_DEFINE_ASSERT_LE)
#define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
#endif
-#if !GTEST_DONT_DEFINE_ASSERT_LT
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_LT) && GTEST_DONT_DEFINE_ASSERT_LT)
#define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
#endif
-#if !GTEST_DONT_DEFINE_ASSERT_GE
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_GE) && GTEST_DONT_DEFINE_ASSERT_GE)
#define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
#endif
-#if !GTEST_DONT_DEFINE_ASSERT_GT
+#if !(defined(GTEST_DONT_DEFINE_ASSERT_GT) && GTEST_DONT_DEFINE_ASSERT_GT)
#define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
#endif
@@ -1981,7 +1999,7 @@ GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
double val1, double val2);
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Macros that test for HRESULT failure and success, these are only useful
// on Windows, and rely on Windows SDK macros and APIs to compile.
@@ -2063,9 +2081,7 @@ class GTEST_API_ ScopedTrace {
ScopedTrace(const ScopedTrace&) = delete;
ScopedTrace& operator=(const ScopedTrace&) = delete;
-} GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
- // c'tor and d'tor. Therefore it doesn't
- // need to be used otherwise.
+};
// Causes a trace (including the source file path, the current line
// number, and the given message) to be included in every test failure
@@ -2153,7 +2169,7 @@ constexpr bool StaticAssertTypeEq() noexcept {
// Define this macro to 1 to omit the definition of TEST(), which
// is a generic name and clashes with some other libraries.
-#if !GTEST_DONT_DEFINE_TEST
+#if !(defined(GTEST_DONT_DEFINE_TEST) && GTEST_DONT_DEFINE_TEST)
#define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
#endif
@@ -2185,17 +2201,22 @@ constexpr bool StaticAssertTypeEq() noexcept {
#define GTEST_TEST_F(test_fixture, test_name) \
GTEST_TEST_(test_fixture, test_name, test_fixture, \
::testing::internal::GetTypeId<test_fixture>())
-#if !GTEST_DONT_DEFINE_TEST_F
+#if !(defined(GTEST_DONT_DEFINE_TEST_F) && GTEST_DONT_DEFINE_TEST_F)
#define TEST_F(test_fixture, test_name) GTEST_TEST_F(test_fixture, test_name)
#endif
-// Returns a path to temporary directory.
-// Tries to determine an appropriate directory for the platform.
+// Returns a path to a temporary directory, which should be writable. It is
+// implementation-dependent whether or not the path is terminated by the
+// directory-separator character.
GTEST_API_ std::string TempDir();
-#ifdef _MSC_VER
-#pragma warning(pop)
-#endif
+// Returns a path to a directory that contains ancillary data files that might
+// be used by tests. It is implementation dependent whether or not the path is
+// terminated by the directory-separator character. The directory and the files
+// in it should be considered read-only.
+GTEST_API_ std::string SrcDir();
+
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4805 4100
// Dynamically registers a test with the framework.
//
diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h
index 45580ae..522eed8 100644
--- a/googletest/include/gtest/internal/gtest-death-test-internal.h
+++ b/googletest/include/gtest/internal/gtest-death-test-internal.h
@@ -42,6 +42,7 @@
#include <stdio.h>
#include <memory>
+#include <string>
#include "gtest/gtest-matchers.h"
#include "gtest/internal/gtest-internal.h"
@@ -56,7 +57,7 @@ const char kDeathTestStyleFlag[] = "death_test_style";
const char kDeathTestUseFork[] = "death_test_use_fork";
const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
@@ -99,7 +100,7 @@ class GTEST_API_ DeathTest {
DeathTest* const test_;
ReturnSentinel(const ReturnSentinel&) = delete;
ReturnSentinel& operator=(const ReturnSentinel&) = delete;
- } GTEST_ATTRIBUTE_UNUSED_;
+ };
// An enumeration of possible roles that may be taken when a death
// test is encountered. EXECUTE means that the death test logic should
@@ -237,7 +238,7 @@ inline Matcher<const ::std::string&> MakeDeathTestMatcher(
} \
break; \
case ::testing::internal::DeathTest::EXECUTE_TEST: { \
- ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
+ const ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
gtest_dt); \
GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
diff --git a/googletest/include/gtest/internal/gtest-filepath.h b/googletest/include/gtest/internal/gtest-filepath.h
index a2a60a9..5189c81 100644
--- a/googletest/include/gtest/internal/gtest-filepath.h
+++ b/googletest/include/gtest/internal/gtest-filepath.h
@@ -42,11 +42,16 @@
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
+#include <string>
+
+#include "gtest/internal/gtest-port.h"
#include "gtest/internal/gtest-string.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
+#if GTEST_HAS_FILE_SYSTEM
+
namespace testing {
namespace internal {
@@ -199,6 +204,16 @@ class GTEST_API_ FilePath {
// separators. Returns NULL if no path separator was found.
const char* FindLastPathSeparator() const;
+ // Returns the length of the path root, including the directory separator at
+ // the end of the prefix. Returns zero by definition if the path is relative.
+ // Examples:
+ // - [Windows] "..\Sibling" => 0
+ // - [Windows] "\Windows" => 1
+ // - [Windows] "C:/Windows\Notepad.exe" => 3
+ // - [Windows] "\\Host\Share\C$/Windows" => 13
+ // - [UNIX] "/bin" => 1
+ size_t CalculateRootLength() const;
+
std::string pathname_;
}; // class FilePath
@@ -207,4 +222,6 @@ class GTEST_API_ FilePath {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
+#endif // GTEST_HAS_FILE_SYSTEM
+
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h
index e9c2441..ae2ca95 100644
--- a/googletest/include/gtest/internal/gtest-internal.h
+++ b/googletest/include/gtest/internal/gtest-internal.h
@@ -41,7 +41,7 @@
#include "gtest/internal/gtest-port.h"
-#if GTEST_OS_LINUX
+#ifdef GTEST_OS_LINUX
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
@@ -64,6 +64,7 @@
#include <set>
#include <string>
#include <type_traits>
+#include <utility>
#include <vector>
#include "gtest/gtest-message.h"
@@ -306,9 +307,6 @@ class FloatingPoint {
// Returns the floating-point number that represent positive infinity.
static RawType Infinity() { return ReinterpretBits(kExponentBitMask); }
- // Returns the maximum representable finite floating-point number.
- static RawType Max();
-
// Non-static methods
// Returns the bits that represents this number.
@@ -389,17 +387,6 @@ class FloatingPoint {
FloatingPointUnion u_;
};
-// We cannot use std::numeric_limits<T>::max() as it clashes with the max()
-// macro defined by <windows.h>.
-template <>
-inline float FloatingPoint<float>::Max() {
- return FLT_MAX;
-}
-template <>
-inline double FloatingPoint<double>::Max() {
- return DBL_MAX;
-}
-
// Typedefs the instances of the FloatingPoint template class that we
// care to use.
typedef FloatingPoint<float> Float;
@@ -470,7 +457,7 @@ class TestFactoryImpl : public TestFactoryBase {
Test* CreateTest() override { return new TestClass; }
};
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Predicate-formatters for implementing the HRESULT checking macros
// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
@@ -913,8 +900,10 @@ class HasDebugStringAndShortDebugString {
HasDebugStringType::value && HasShortDebugStringType::value;
};
+#ifdef GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
template <typename T>
constexpr bool HasDebugStringAndShortDebugString<T>::value;
+#endif
// When the compiler sees expression IsContainerTest<C>(0), if C is an
// STL-style container class, the first overload of IsContainerTest
diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h
index e7af2f9..50435f5 100644
--- a/googletest/include/gtest/internal/gtest-param-util.h
+++ b/googletest/include/gtest/internal/gtest-param-util.h
@@ -40,8 +40,11 @@
#include <cassert>
#include <iterator>
+#include <map>
#include <memory>
+#include <ostream>
#include <set>
+#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
@@ -791,10 +794,7 @@ internal::ParamGenerator<typename Container::value_type> ValuesIn(
namespace internal {
// Used in the Values() function to provide polymorphic capabilities.
-#ifdef _MSC_VER
-#pragma warning(push)
-#pragma warning(disable : 4100)
-#endif
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
template <typename... Ts>
class ValueArray {
@@ -815,9 +815,7 @@ class ValueArray {
FlatTuple<Ts...> v_;
};
-#ifdef _MSC_VER
-#pragma warning(pop)
-#endif
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
template <typename... T>
class CartesianProductGenerator
@@ -950,6 +948,78 @@ class CartesianProductHolder {
std::tuple<Gen...> generators_;
};
+template <typename From, typename To>
+class ParamGeneratorConverter : public ParamGeneratorInterface<To> {
+ public:
+ ParamGeneratorConverter(ParamGenerator<From> gen) // NOLINT
+ : generator_(std::move(gen)) {}
+
+ ParamIteratorInterface<To>* Begin() const override {
+ return new Iterator(this, generator_.begin(), generator_.end());
+ }
+ ParamIteratorInterface<To>* End() const override {
+ return new Iterator(this, generator_.end(), generator_.end());
+ }
+
+ private:
+ class Iterator : public ParamIteratorInterface<To> {
+ public:
+ Iterator(const ParamGeneratorInterface<To>* base, ParamIterator<From> it,
+ ParamIterator<From> end)
+ : base_(base), it_(it), end_(end) {
+ if (it_ != end_) value_ = std::make_shared<To>(static_cast<To>(*it_));
+ }
+ ~Iterator() override {}
+
+ const ParamGeneratorInterface<To>* BaseGenerator() const override {
+ return base_;
+ }
+ void Advance() override {
+ ++it_;
+ if (it_ != end_) value_ = std::make_shared<To>(static_cast<To>(*it_));
+ }
+ ParamIteratorInterface<To>* Clone() const override {
+ return new Iterator(*this);
+ }
+ const To* Current() const override { return value_.get(); }
+ bool Equals(const ParamIteratorInterface<To>& other) const override {
+ // Having the same base generator guarantees that the other
+ // iterator is of the same type and we can downcast.
+ GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
+ << "The program attempted to compare iterators "
+ << "from different generators." << std::endl;
+ const ParamIterator<From> other_it =
+ CheckedDowncastToActualType<const Iterator>(&other)->it_;
+ return it_ == other_it;
+ }
+
+ private:
+ Iterator(const Iterator& other) = default;
+
+ const ParamGeneratorInterface<To>* const base_;
+ ParamIterator<From> it_;
+ ParamIterator<From> end_;
+ std::shared_ptr<To> value_;
+ }; // class ParamGeneratorConverter::Iterator
+
+ ParamGenerator<From> generator_;
+}; // class ParamGeneratorConverter
+
+template <class Gen>
+class ParamConverterGenerator {
+ public:
+ ParamConverterGenerator(ParamGenerator<Gen> g) // NOLINT
+ : generator_(std::move(g)) {}
+
+ template <typename T>
+ operator ParamGenerator<T>() const { // NOLINT
+ return ParamGenerator<T>(new ParamGeneratorConverter<Gen, T>(generator_));
+ }
+
+ private:
+ ParamGenerator<Gen> generator_;
+};
+
} // namespace internal
} // namespace testing
diff --git a/googletest/include/gtest/internal/gtest-port-arch.h b/googletest/include/gtest/internal/gtest-port-arch.h
index f025db7..0406460 100644
--- a/googletest/include/gtest/internal/gtest-port-arch.h
+++ b/googletest/include/gtest/internal/gtest-port-arch.h
@@ -111,6 +111,8 @@
#define GTEST_OS_ESP32 1
#elif defined(__XTENSA__)
#define GTEST_OS_XTENSA 1
+#elif defined(__hexagon__)
+#define GTEST_OS_QURT 1
#endif // __CYGWIN__
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h
index c9e1f32..656a261 100644
--- a/googletest/include/gtest/internal/gtest-port.h
+++ b/googletest/include/gtest/internal/gtest-port.h
@@ -83,6 +83,8 @@
// GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that
// std::wstring does/doesn't work (Google Test can
// be used where std::wstring is unavailable).
+// GTEST_HAS_FILE_SYSTEM - Define it to 1/0 to indicate whether or not a
+// file system is/isn't available.
// GTEST_HAS_SEH - Define it to 1/0 to indicate whether the
// compiler supports Microsoft's "Structured
// Exception Handling".
@@ -159,10 +161,10 @@
// NOT define them.
//
// These macros are public so that portable tests can be written.
-// Such tests typically surround code using a feature with an #if
+// Such tests typically surround code using a feature with an #ifdef
// which controls that code. For example:
//
-// #if GTEST_HAS_DEATH_TEST
+// #ifdef GTEST_HAS_DEATH_TEST
// EXPECT_DEATH(DoSomethingDeadly());
// #endif
//
@@ -176,6 +178,7 @@
// define themselves.
// GTEST_USES_SIMPLE_RE - our own simple regex is used;
// the above RE\b(s) are mutually exclusive.
+// GTEST_HAS_ABSL - Google Test is compiled with Abseil.
// Misc public macros
// ------------------
@@ -200,16 +203,25 @@
// is suppressed.
// GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter<std::any> or
// UniversalPrinter<absl::any> specializations.
+// Always defined to 0 or 1.
// GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional>
// or
// UniversalPrinter<absl::optional>
-// specializations.
+// specializations. Always defined to 0 or 1.
// GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or
// Matcher<absl::string_view>
-// specializations.
+// specializations. Always defined to 0 or 1.
// GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter<std::variant> or
// UniversalPrinter<absl::variant>
-// specializations.
+// specializations. Always defined to 0 or 1.
+// GTEST_USE_OWN_FLAGFILE_FLAG_ - Always defined to 0 or 1.
+// GTEST_HAS_CXXABI_H_ - Always defined to 0 or 1.
+// GTEST_CAN_STREAM_RESULTS_ - Always defined to 0 or 1.
+// GTEST_HAS_ALT_PATH_SEP_ - Always defined to 0 or 1.
+// GTEST_WIDE_STRING_USES_UTF16_ - Always defined to 0 or 1.
+// GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Always defined to 0 or 1.
+// GTEST_HAS_DOWNCAST_ - Always defined to 0 or 1.
+// GTEST_HAS_NOTIFICATION_- Always defined to 0 or 1.
//
// Synchronization:
// Mutex, MutexLock, ThreadLocal, GetThreadCount()
@@ -255,6 +267,19 @@
// deprecated; calling a marked function
// should generate a compiler warning
+// The definition of GTEST_INTERNAL_CPLUSPLUS_LANG comes first because it can
+// potentially be used as an #include guard.
+#if defined(_MSVC_LANG)
+#define GTEST_INTERNAL_CPLUSPLUS_LANG _MSVC_LANG
+#elif defined(__cplusplus)
+#define GTEST_INTERNAL_CPLUSPLUS_LANG __cplusplus
+#endif
+
+#if !defined(GTEST_INTERNAL_CPLUSPLUS_LANG) || \
+ GTEST_INTERNAL_CPLUSPLUS_LANG < 201402L
+#error C++ versions less than C++14 are not supported.
+#endif
+
#include <ctype.h> // for isspace, etc
#include <stddef.h> // for ptrdiff_t
#include <stdio.h>
@@ -268,6 +293,7 @@
#include <limits>
#include <locale>
#include <memory>
+#include <ostream>
#include <string>
// #include <mutex> // Guarded by GTEST_IS_THREADSAFE below
#include <tuple>
@@ -287,7 +313,19 @@
#include "gtest/internal/custom/gtest-port.h"
#include "gtest/internal/gtest-port-arch.h"
-#if GTEST_HAS_ABSL
+#ifndef GTEST_HAS_DOWNCAST_
+#define GTEST_HAS_DOWNCAST_ 0
+#endif
+
+#ifndef GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
+#define GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ 0
+#endif
+
+#ifndef GTEST_HAS_NOTIFICATION_
+#define GTEST_HAS_NOTIFICATION_ 0
+#endif
+
+#ifdef GTEST_HAS_ABSL
#include "absl/flags/declare.h"
#include "absl/flags/flag.h"
#include "absl/flags/reflection.h"
@@ -345,13 +383,13 @@
// Brings in definitions for functions used in the testing::internal::posix
// namespace (read, write, close, chdir, isatty, stat). We do not currently
// use them on Windows Mobile.
-#if GTEST_OS_WINDOWS
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS
+#ifndef GTEST_OS_WINDOWS_MOBILE
#include <direct.h>
#include <io.h>
#endif
// In order to avoid having to include <windows.h>, use forward declaration
-#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
+#if defined(GTEST_OS_WINDOWS_MINGW) && !defined(__MINGW64_VERSION_MAJOR)
// MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two
// separate (equivalent) structs, instead of using typedef
typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION;
@@ -361,7 +399,7 @@ typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#endif
-#elif GTEST_OS_XTENSA
+#elif defined(GTEST_OS_XTENSA)
#include <unistd.h>
// Xtensa toolchains define strcasecmp in the string.h header instead of
// strings.h. string.h is already included.
@@ -373,7 +411,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#include <unistd.h>
#endif // GTEST_OS_WINDOWS
-#if GTEST_OS_LINUX_ANDROID
+#ifdef GTEST_OS_LINUX_ANDROID
// Used to define __ANDROID_API__ matching the target NDK API level.
#include <android/api-level.h> // NOLINT
#endif
@@ -381,16 +419,21 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// Defines this to true if and only if Google Test can use POSIX regular
// expressions.
#ifndef GTEST_HAS_POSIX_RE
-#if GTEST_OS_LINUX_ANDROID
+#ifdef GTEST_OS_LINUX_ANDROID
// On Android, <regex.h> is only available starting with Gingerbread.
#define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
#else
-#define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS && !GTEST_OS_XTENSA)
+#if !(defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_XTENSA) || \
+ defined(GTEST_OS_QURT))
+#define GTEST_HAS_POSIX_RE 1
+#else
+#define GTEST_HAS_POSIX_RE 0
#endif
+#endif // GTEST_OS_LINUX_ANDROID
#endif
// Select the regular expression implementation.
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
// When using Abseil, RE2 is required.
#include "absl/strings/string_view.h"
#include "re2/re2.h"
@@ -426,8 +469,12 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// cleanups prior to that. To reliably check for C++ exception availability with
// clang, check for
// __EXCEPTIONS && __has_feature(cxx_exceptions).
-#define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
-#elif defined(__GNUC__) && __EXCEPTIONS
+#if defined(__EXCEPTIONS) && __EXCEPTIONS && __has_feature(cxx_exceptions)
+#define GTEST_HAS_EXCEPTIONS 1
+#else
+#define GTEST_HAS_EXCEPTIONS 0
+#endif
+#elif defined(__GNUC__) && defined(__EXCEPTIONS) && __EXCEPTIONS
// gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
#define GTEST_HAS_EXCEPTIONS 1
#elif defined(__SUNPRO_CC)
@@ -435,7 +482,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// detecting whether they are enabled or not. Therefore, we assume that
// they are enabled unless the user tells us otherwise.
#define GTEST_HAS_EXCEPTIONS 1
-#elif defined(__IBMCPP__) && __EXCEPTIONS
+#elif defined(__IBMCPP__) && defined(__EXCEPTIONS) && __EXCEPTIONS
// xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
#define GTEST_HAS_EXCEPTIONS 1
#elif defined(__HP_aCC)
@@ -455,12 +502,21 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// Cygwin 1.7 and below doesn't support ::std::wstring.
// Solaris' libc++ doesn't support it either. Android has
// no support for it at least as recent as Froyo (2.2).
-#define GTEST_HAS_STD_WSTRING \
- (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
- GTEST_OS_HAIKU || GTEST_OS_ESP32 || GTEST_OS_ESP8266 || GTEST_OS_XTENSA))
-
+#if (!(defined(GTEST_OS_LINUX_ANDROID) || defined(GTEST_OS_CYGWIN) || \
+ defined(GTEST_OS_SOLARIS) || defined(GTEST_OS_HAIKU) || \
+ defined(GTEST_OS_ESP32) || defined(GTEST_OS_ESP8266) || \
+ defined(GTEST_OS_XTENSA) || defined(GTEST_OS_QURT)))
+#define GTEST_HAS_STD_WSTRING 1
+#else
+#define GTEST_HAS_STD_WSTRING 0
+#endif
#endif // GTEST_HAS_STD_WSTRING
+#ifndef GTEST_HAS_FILE_SYSTEM
+// Most platforms support a file system.
+#define GTEST_HAS_FILE_SYSTEM 1
+#endif // GTEST_HAS_FILE_SYSTEM
+
// Determines whether RTTI is available.
#ifndef GTEST_HAS_RTTI
// The user didn't tell us whether RTTI is enabled, so we need to
@@ -483,7 +539,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// -frtti -fno-exceptions, the build fails at link time with undefined
// references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
// so disable RTTI when detected.
-#if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && !defined(__EXCEPTIONS)
+#if defined(GTEST_OS_LINUX_ANDROID) && defined(_STLPORT_MAJOR) && \
+ !defined(__EXCEPTIONS)
#define GTEST_HAS_RTTI 0
#else
#define GTEST_HAS_RTTI 1
@@ -531,11 +588,17 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
//
// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
// to your compiler flags.
-#define GTEST_HAS_PTHREAD \
- (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \
- GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
- GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD || \
- GTEST_OS_HAIKU || GTEST_OS_GNU_HURD)
+#if (defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || \
+ defined(GTEST_OS_HPUX) || defined(GTEST_OS_QNX) || \
+ defined(GTEST_OS_FREEBSD) || defined(GTEST_OS_NACL) || \
+ defined(GTEST_OS_NETBSD) || defined(GTEST_OS_FUCHSIA) || \
+ defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_GNU_KFREEBSD) || \
+ defined(GTEST_OS_OPENBSD) || defined(GTEST_OS_HAIKU) || \
+ defined(GTEST_OS_GNU_HURD))
+#define GTEST_HAS_PTHREAD 1
+#else
+#define GTEST_HAS_PTHREAD 0
+#endif
#endif // GTEST_HAS_PTHREAD
#if GTEST_HAS_PTHREAD
@@ -554,8 +617,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#ifndef GTEST_HAS_CLONE
// The user didn't tell us, so we need to figure it out.
-#if GTEST_OS_LINUX && !defined(__ia64__)
-#if GTEST_OS_LINUX_ANDROID
+#if defined(GTEST_OS_LINUX) && !defined(__ia64__)
+#if defined(GTEST_OS_LINUX_ANDROID)
// On Android, clone() became available at different API levels for each 32-bit
// architecture.
#if defined(__LP64__) || (defined(__arm__) && __ANDROID_API__ >= 9) || \
@@ -578,9 +641,12 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// output correctness and to implement death tests.
#ifndef GTEST_HAS_STREAM_REDIRECTION
// By default, we assume that stream redirection is supported on all
-// platforms except known mobile ones.
-#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
- GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
+// platforms except known mobile / embedded ones. Also, if the port doesn't have
+// a file system, stream redirection is not supported.
+#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \
+ defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_ESP8266) || \
+ defined(GTEST_OS_XTENSA) || defined(GTEST_OS_QURT) || \
+ !GTEST_HAS_FILE_SYSTEM
#define GTEST_HAS_STREAM_REDIRECTION 0
#else
#define GTEST_HAS_STREAM_REDIRECTION 1
@@ -589,14 +655,20 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// Determines whether to support death tests.
// pops up a dialog window that cannot be suppressed programmatically.
-#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
- (GTEST_OS_MAC && !GTEST_OS_IOS) || \
- (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW || \
- GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \
- GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
- GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU || \
- GTEST_OS_GNU_HURD)
+#if (defined(GTEST_OS_LINUX) || defined(GTEST_OS_CYGWIN) || \
+ defined(GTEST_OS_SOLARIS) || \
+ (defined(GTEST_OS_MAC) && !defined(GTEST_OS_IOS)) || \
+ (defined(GTEST_OS_WINDOWS_DESKTOP) && _MSC_VER) || \
+ defined(GTEST_OS_WINDOWS_MINGW) || defined(GTEST_OS_AIX) || \
+ defined(GTEST_OS_HPUX) || defined(GTEST_OS_OPENBSD) || \
+ defined(GTEST_OS_QNX) || defined(GTEST_OS_FREEBSD) || \
+ defined(GTEST_OS_NETBSD) || defined(GTEST_OS_FUCHSIA) || \
+ defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_GNU_KFREEBSD) || \
+ defined(GTEST_OS_HAIKU) || defined(GTEST_OS_GNU_HURD))
+// Death tests require a file system to work properly.
+#if GTEST_HAS_FILE_SYSTEM
#define GTEST_HAS_DEATH_TEST 1
+#endif // GTEST_HAS_FILE_SYSTEM
#endif
// Determines whether to support type-driven tests.
@@ -610,14 +682,21 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#endif
// Determines whether the system compiler uses UTF-16 for encoding wide strings.
-#define GTEST_WIDE_STRING_USES_UTF16_ \
- (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2)
+#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_CYGWIN) || \
+ defined(GTEST_OS_AIX) || defined(GTEST_OS_OS2)
+#define GTEST_WIDE_STRING_USES_UTF16_ 1
+#else
+#define GTEST_WIDE_STRING_USES_UTF16_ 0
+#endif
// Determines whether test results can be streamed to a socket.
-#if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \
- GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD || \
- GTEST_OS_GNU_HURD
+#if defined(GTEST_OS_LINUX) || defined(GTEST_OS_GNU_KFREEBSD) || \
+ defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
+ defined(GTEST_OS_NETBSD) || defined(GTEST_OS_OPENBSD) || \
+ defined(GTEST_OS_GNU_HURD) || defined(GTEST_OS_MAC)
#define GTEST_CAN_STREAM_RESULTS_ 1
+#else
+#define GTEST_CAN_STREAM_RESULTS_ 0
#endif
// Defines some utility macros.
@@ -639,41 +718,53 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
default: // NOLINT
#endif
-// Use this annotation at the end of a struct/class definition to
-// prevent the compiler from optimizing away instances that are never
-// used. This is useful when all interesting logic happens inside the
-// c'tor and / or d'tor. Example:
+// GTEST_HAVE_ATTRIBUTE_
//
-// struct Foo {
-// Foo() { ... }
-// } GTEST_ATTRIBUTE_UNUSED_;
+// A function-like feature checking macro that is a wrapper around
+// `__has_attribute`, which is defined by GCC 5+ and Clang and evaluates to a
+// nonzero constant integer if the attribute is supported or 0 if not.
//
-// Also use it after a variable or parameter declaration to tell the
-// compiler the variable/parameter does not have to be used.
-#if defined(__GNUC__) && !defined(COMPILER_ICC)
-#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused))
-#elif defined(__clang__)
-#if __has_attribute(unused)
-#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused))
+// It evaluates to zero if `__has_attribute` is not defined by the compiler.
+//
+// GCC: https://gcc.gnu.org/gcc-5/changes.html
+// Clang: https://clang.llvm.org/docs/LanguageExtensions.html
+#ifdef __has_attribute
+#define GTEST_HAVE_ATTRIBUTE_(x) __has_attribute(x)
+#else
+#define GTEST_HAVE_ATTRIBUTE_(x) 0
#endif
+
+// GTEST_HAVE_FEATURE_
+//
+// A function-like feature checking macro that is a wrapper around
+// `__has_feature`.
+#ifdef __has_feature
+#define GTEST_HAVE_FEATURE_(x) __has_feature(x)
+#else
+#define GTEST_HAVE_FEATURE_(x) 0
#endif
-#ifndef GTEST_ATTRIBUTE_UNUSED_
+
+// Use this annotation after a variable or parameter declaration to tell the
+// compiler the variable/parameter does not have to be used.
+// Example:
+//
+// GTEST_ATTRIBUTE_UNUSED_ int foo = bar();
+#if GTEST_HAVE_ATTRIBUTE_(unused)
+#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused))
+#else
#define GTEST_ATTRIBUTE_UNUSED_
#endif
// Use this annotation before a function that takes a printf format string.
-#if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC)
-#if defined(__MINGW_PRINTF_FORMAT)
+#if GTEST_HAVE_ATTRIBUTE_(format) && defined(__MINGW_PRINTF_FORMAT)
// MinGW has two different printf implementations. Ensure the format macro
// matches the selected implementation. See
// https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/.
#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
- __attribute__(( \
- __format__(__MINGW_PRINTF_FORMAT, string_index, first_to_check)))
-#else
+ __attribute__((format(__MINGW_PRINTF_FORMAT, string_index, first_to_check)))
+#elif GTEST_HAVE_ATTRIBUTE_(format)
#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
- __attribute__((__format__(__printf__, string_index, first_to_check)))
-#endif
+ __attribute__((format(printf, string_index, first_to_check)))
#else
#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
#endif
@@ -683,11 +774,11 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// following the argument list:
//
// Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
-#if defined(__GNUC__) && !defined(COMPILER_ICC)
+#if GTEST_HAVE_ATTRIBUTE_(warn_unused_result)
#define GTEST_MUST_USE_RESULT_ __attribute__((warn_unused_result))
#else
#define GTEST_MUST_USE_RESULT_
-#endif // __GNUC__ && !COMPILER_ICC
+#endif
// MS C++ compiler emits warning when a conditional expression is compile time
// constant. In some contexts this warning is false positive and needs to be
@@ -719,14 +810,16 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#ifndef GTEST_IS_THREADSAFE
-#define GTEST_IS_THREADSAFE \
- (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \
- (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) || \
- GTEST_HAS_PTHREAD)
+#if (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \
+ (defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_PHONE) && \
+ !defined(GTEST_OS_WINDOWS_RT)) || \
+ GTEST_HAS_PTHREAD)
+#define GTEST_IS_THREADSAFE 1
+#endif
#endif // GTEST_IS_THREADSAFE
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
// Some platforms don't support including these threading related headers.
#include <condition_variable> // NOLINT
#include <mutex> // NOLINT
@@ -743,7 +836,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#elif GTEST_CREATE_SHARED_LIBRARY
#define GTEST_API_ __declspec(dllexport)
#endif
-#elif __GNUC__ >= 4 || defined(__clang__)
+#elif GTEST_HAVE_ATTRIBUTE_(visibility)
#define GTEST_API_ __attribute__((visibility("default")))
#endif // _MSC_VER
@@ -757,21 +850,18 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#define GTEST_DEFAULT_DEATH_TEST_STYLE "fast"
#endif // GTEST_DEFAULT_DEATH_TEST_STYLE
-#ifdef __GNUC__
+#if GTEST_HAVE_ATTRIBUTE_(noinline)
// Ask the compiler to never inline a given function.
#define GTEST_NO_INLINE_ __attribute__((noinline))
#else
#define GTEST_NO_INLINE_
#endif
-#if defined(__clang__)
-// Nested ifs to avoid triggering MSVC warning.
-#if __has_attribute(disable_tail_calls)
+#if GTEST_HAVE_ATTRIBUTE_(disable_tail_calls)
// Ask the compiler not to perform tail call optimization inside
// the marked function.
#define GTEST_NO_TAIL_CALL_ __attribute__((disable_tail_calls))
-#endif
-#elif __GNUC__
+#elif defined(__GNUC__) && !defined(__NVCOMPILER)
#define GTEST_NO_TAIL_CALL_ \
__attribute__((optimize("no-optimize-sibling-calls")))
#else
@@ -789,50 +879,35 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// A function level attribute to disable checking for use of uninitialized
// memory when built with MemorySanitizer.
-#if defined(__clang__)
-#if __has_feature(memory_sanitizer)
+#if GTEST_HAVE_ATTRIBUTE_(no_sanitize_memory)
#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ __attribute__((no_sanitize_memory))
#else
#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
-#endif // __has_feature(memory_sanitizer)
-#else
-#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
-#endif // __clang__
+#endif
// A function level attribute to disable AddressSanitizer instrumentation.
-#if defined(__clang__)
-#if __has_feature(address_sanitizer)
+#if GTEST_HAVE_ATTRIBUTE_(no_sanitize_address)
#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
__attribute__((no_sanitize_address))
#else
#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
-#endif // __has_feature(address_sanitizer)
-#else
-#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
-#endif // __clang__
+#endif
// A function level attribute to disable HWAddressSanitizer instrumentation.
-#if defined(__clang__)
-#if __has_feature(hwaddress_sanitizer)
+#if GTEST_HAVE_FEATURE_(hwaddress_sanitizer) && \
+ GTEST_HAVE_ATTRIBUTE_(no_sanitize)
#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \
__attribute__((no_sanitize("hwaddress")))
#else
#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
-#endif // __has_feature(hwaddress_sanitizer)
-#else
-#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
-#endif // __clang__
+#endif
// A function level attribute to disable ThreadSanitizer instrumentation.
-#if defined(__clang__)
-#if __has_feature(thread_sanitizer)
-#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ __attribute__((no_sanitize_thread))
-#else
-#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
-#endif // __has_feature(thread_sanitizer)
+#if GTEST_HAVE_ATTRIBUTE_(no_sanitize_thread)
+#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ __attribute((no_sanitize_thread))
#else
#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
-#endif // __clang__
+#endif
namespace testing {
@@ -859,7 +934,7 @@ GTEST_API_ bool IsTrue(bool condition);
// Defines RE.
-#if GTEST_USES_RE2
+#ifdef GTEST_USES_RE2
// This is almost `using RE = ::RE2`, except it is copy-constructible, and it
// needs to disambiguate the `std::string`, `absl::string_view`, and `const
@@ -884,7 +959,9 @@ class GTEST_API_ RE {
RE2 regex_;
};
-#elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE
+#elif defined(GTEST_USES_POSIX_RE) || defined(GTEST_USES_SIMPLE_RE)
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
+/* class A needs to have dll-interface to be used by clients of class B */)
// A simple C++ wrapper for <regex.h>. It uses the POSIX Extended
// Regular Expression syntax.
@@ -901,7 +978,7 @@ class GTEST_API_ RE {
~RE();
// Returns the string representation of the regex.
- const char* pattern() const { return pattern_; }
+ const char* pattern() const { return pattern_.c_str(); }
// FullMatch(str, re) returns true if and only if regular expression re
// matches the entire str.
@@ -919,21 +996,21 @@ class GTEST_API_ RE {
private:
void Init(const char* regex);
- const char* pattern_;
+ std::string pattern_;
bool is_valid_;
-#if GTEST_USES_POSIX_RE
+#ifdef GTEST_USES_POSIX_RE
regex_t full_regex_; // For FullMatch().
regex_t partial_regex_; // For PartialMatch().
#else // GTEST_USES_SIMPLE_RE
- const char* full_pattern_; // For FullMatch();
+ std::string full_pattern_; // For FullMatch();
#endif
};
-
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#endif // ::testing::internal::RE implementation
// Formats a source file path and a line number as they would appear
@@ -1150,7 +1227,7 @@ GTEST_API_ std::string ReadEntireFile(FILE* file);
// All command line arguments.
GTEST_API_ std::vector<std::string> GetArgvs();
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
std::vector<std::string> GetInjectableArgvs();
// Deprecated: pass the args vector by value instead.
@@ -1161,9 +1238,9 @@ void ClearInjectableArgvs();
#endif // GTEST_HAS_DEATH_TEST
// Defines synchronization primitives.
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Provides leak-safe Windows kernel handle ownership.
// Used in death tests and in threading support.
class GTEST_API_ AutoHandle {
@@ -1242,7 +1319,7 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
// On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
// defined, but we don't want to use MinGW's pthreads implementation, which
// has conformance problems with some versions of the POSIX standard.
-#if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
+#if GTEST_HAS_PTHREAD && !defined(GTEST_OS_WINDOWS_MINGW)
// As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
// Consequently, it cannot select a correct instantiation of ThreadWithParam
@@ -1328,7 +1405,8 @@ class ThreadWithParam : public ThreadWithParamBase {
// Mutex and ThreadLocal have already been imported into the namespace.
// Nothing to do here.
-#elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
+#elif defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_PHONE) && \
+ !defined(GTEST_OS_WINDOWS_RT)
// Mutex implements mutex on Windows platforms. It is used in conjunction
// with class MutexLock:
@@ -1881,7 +1959,7 @@ class GTEST_API_ ThreadLocal {
// we cannot detect it.
GTEST_API_ size_t GetThreadCount();
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
#define GTEST_PATH_SEP_ "\\"
#define GTEST_HAS_ALT_PATH_SEP_ 1
#else
@@ -1956,32 +2034,13 @@ inline std::string StripTrailingSpaces(std::string str) {
namespace posix {
-// Functions with a different name on Windows.
-
-#if GTEST_OS_WINDOWS
+// File system porting.
+#if GTEST_HAS_FILE_SYSTEM
+#ifdef GTEST_OS_WINDOWS
typedef struct _stat StatStruct;
-#ifdef __BORLANDC__
-inline int DoIsATTY(int fd) { return isatty(fd); }
-inline int StrCaseCmp(const char* s1, const char* s2) {
- return stricmp(s1, s2);
-}
-inline char* StrDup(const char* src) { return strdup(src); }
-#else // !__BORLANDC__
-#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
- GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)
-inline int DoIsATTY(int /* fd */) { return 0; }
-#else
-inline int DoIsATTY(int fd) { return _isatty(fd); }
-#endif // GTEST_OS_WINDOWS_MOBILE
-inline int StrCaseCmp(const char* s1, const char* s2) {
- return _stricmp(s1, s2);
-}
-inline char* StrDup(const char* src) { return _strdup(src); }
-#endif // __BORLANDC__
-
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
// Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
// time and thus not defined there.
@@ -1992,19 +2051,14 @@ inline int RmDir(const char* dir) { return _rmdir(dir); }
inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; }
#endif // GTEST_OS_WINDOWS_MOBILE
-#elif GTEST_OS_ESP8266
+#elif defined(GTEST_OS_ESP8266)
typedef struct stat StatStruct;
inline int FileNo(FILE* file) { return fileno(file); }
-inline int DoIsATTY(int fd) { return isatty(fd); }
inline int Stat(const char* path, StatStruct* buf) {
// stat function not implemented on ESP8266
return 0;
}
-inline int StrCaseCmp(const char* s1, const char* s2) {
- return strcasecmp(s1, s2);
-}
-inline char* StrDup(const char* src) { return strdup(src); }
inline int RmDir(const char* dir) { return rmdir(dir); }
inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
@@ -2013,14 +2067,46 @@ inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
typedef struct stat StatStruct;
inline int FileNo(FILE* file) { return fileno(file); }
-inline int DoIsATTY(int fd) { return isatty(fd); }
inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
+#ifdef GTEST_OS_QURT
+// QuRT doesn't support any directory functions, including rmdir
+inline int RmDir(const char*) { return 0; }
+#else
+inline int RmDir(const char* dir) { return rmdir(dir); }
+#endif
+inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
+
+#endif // GTEST_OS_WINDOWS
+#endif // GTEST_HAS_FILE_SYSTEM
+
+// Other functions with a different name on Windows.
+
+#ifdef GTEST_OS_WINDOWS
+
+#ifdef __BORLANDC__
+inline int DoIsATTY(int fd) { return isatty(fd); }
+inline int StrCaseCmp(const char* s1, const char* s2) {
+ return stricmp(s1, s2);
+}
+#else // !__BORLANDC__
+#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_ZOS) || \
+ defined(GTEST_OS_IOS) || defined(GTEST_OS_WINDOWS_PHONE) || \
+ defined(GTEST_OS_WINDOWS_RT) || defined(ESP_PLATFORM)
+inline int DoIsATTY(int /* fd */) { return 0; }
+#else
+inline int DoIsATTY(int fd) { return _isatty(fd); }
+#endif // GTEST_OS_WINDOWS_MOBILE
+inline int StrCaseCmp(const char* s1, const char* s2) {
+ return _stricmp(s1, s2);
+}
+#endif // __BORLANDC__
+
+#else
+
+inline int DoIsATTY(int fd) { return isatty(fd); }
inline int StrCaseCmp(const char* s1, const char* s2) {
return strcasecmp(s1, s2);
}
-inline char* StrDup(const char* src) { return strdup(src); }
-inline int RmDir(const char* dir) { return rmdir(dir); }
-inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
#endif // GTEST_OS_WINDOWS
@@ -2042,13 +2128,14 @@ GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
// ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and
// StrError() aren't needed on Windows CE at this time and thus not
// defined there.
-
-#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
- !GTEST_OS_WINDOWS_RT && !GTEST_OS_ESP8266 && !GTEST_OS_XTENSA
+#if GTEST_HAS_FILE_SYSTEM
+#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_WINDOWS_PHONE) && \
+ !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_ESP8266) && \
+ !defined(GTEST_OS_XTENSA) && !defined(GTEST_OS_QURT)
inline int ChDir(const char* dir) { return chdir(dir); }
#endif
inline FILE* FOpen(const char* path, const char* mode) {
-#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
+#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW)
struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {};
std::wstring_convert<wchar_codecvt> converter;
std::wstring wide_path = converter.from_bytes(path);
@@ -2058,14 +2145,14 @@ inline FILE* FOpen(const char* path, const char* mode) {
return fopen(path, mode);
#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
}
-#if !GTEST_OS_WINDOWS_MOBILE
+#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_QURT)
inline FILE* FReopen(const char* path, const char* mode, FILE* stream) {
return freopen(path, mode, stream);
}
inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
-#endif
+#endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_QURT
inline int FClose(FILE* fp) { return fclose(fp); }
-#if !GTEST_OS_WINDOWS_MOBILE
+#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_QURT)
inline int Read(int fd, void* buf, unsigned int count) {
return static_cast<int>(read(fd, buf, count));
}
@@ -2073,11 +2160,17 @@ inline int Write(int fd, const void* buf, unsigned int count) {
return static_cast<int>(write(fd, buf, count));
}
inline int Close(int fd) { return close(fd); }
+#endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_QURT
+#endif // GTEST_HAS_FILE_SYSTEM
+
+#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_QURT)
inline const char* StrError(int errnum) { return strerror(errnum); }
-#endif
+#endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_QURT
+
inline const char* GetEnv(const char* name) {
-#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
- GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
+#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \
+ defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \
+ defined(GTEST_OS_QURT)
// We are on an embedded platform, which has no environment variables.
static_cast<void>(name); // To prevent 'unused argument' warning.
return nullptr;
@@ -2093,7 +2186,7 @@ inline const char* GetEnv(const char* name) {
GTEST_DISABLE_MSC_DEPRECATED_POP_()
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
// Windows CE has no C library. The abort() function is used in
// several places in Google Test. This implementation provides a reasonable
// imitation of standard behaviour.
@@ -2109,7 +2202,7 @@ GTEST_DISABLE_MSC_DEPRECATED_POP_()
// MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate
// function in order to achieve that. We use macro definition here because
// snprintf is a variadic function.
-#if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE
+#if defined(_MSC_VER) && !defined(GTEST_OS_WINDOWS_MOBILE)
// MSVC 2005 and above support variadic macros.
#define GTEST_SNPRINTF_(buffer, size, format, ...) \
_snprintf_s(buffer, size, size, format, __VA_ARGS__)
@@ -2182,7 +2275,7 @@ using TimeInMillis = int64_t; // Represents time in milliseconds.
#endif // !defined(GTEST_FLAG)
// Pick a command line flags implementation.
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
// Macros for defining flags.
#define GTEST_DEFINE_bool_(name, default_val, doc) \
@@ -2293,7 +2386,7 @@ const char* StringFromGTestEnv(const char* flag, const char* default_val);
#endif // !defined(GTEST_INTERNAL_DEPRECATED)
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
// Always use absl::any for UniversalPrinter<> specializations if googletest
// is built with absl support.
#define GTEST_INTERNAL_HAS_ANY 1
@@ -2305,7 +2398,8 @@ using Any = ::absl::any;
} // namespace testing
#else
#ifdef __has_include
-#if __has_include(<any>) && __cplusplus >= 201703L
+#if __has_include(<any>) && __cplusplus >= 201703L && \
+ (!defined(_MSC_VER) || GTEST_HAS_RTTI)
// Otherwise for C++17 and higher use std::any for UniversalPrinter<>
// specializations.
#define GTEST_INTERNAL_HAS_ANY 1
@@ -2321,7 +2415,11 @@ using Any = ::std::any;
#endif // __has_include
#endif // GTEST_HAS_ABSL
-#if GTEST_HAS_ABSL
+#ifndef GTEST_INTERNAL_HAS_ANY
+#define GTEST_INTERNAL_HAS_ANY 0
+#endif
+
+#ifdef GTEST_HAS_ABSL
// Always use absl::optional for UniversalPrinter<> specializations if
// googletest is built with absl support.
#define GTEST_INTERNAL_HAS_OPTIONAL 1
@@ -2353,7 +2451,11 @@ inline ::std::nullopt_t Nullopt() { return ::std::nullopt; }
#endif // __has_include
#endif // GTEST_HAS_ABSL
-#if GTEST_HAS_ABSL
+#ifndef GTEST_INTERNAL_HAS_OPTIONAL
+#define GTEST_INTERNAL_HAS_OPTIONAL 0
+#endif
+
+#ifdef GTEST_HAS_ABSL
// Always use absl::string_view for Matcher<> specializations if googletest
// is built with absl support.
#define GTEST_INTERNAL_HAS_STRING_VIEW 1
@@ -2381,7 +2483,11 @@ using StringView = ::std::string_view;
#endif // __has_include
#endif // GTEST_HAS_ABSL
-#if GTEST_HAS_ABSL
+#ifndef GTEST_INTERNAL_HAS_STRING_VIEW
+#define GTEST_INTERNAL_HAS_STRING_VIEW 0
+#endif
+
+#ifdef GTEST_HAS_ABSL
// Always use absl::variant for UniversalPrinter<> specializations if googletest
// is built with absl support.
#define GTEST_INTERNAL_HAS_VARIANT 1
@@ -2410,4 +2516,13 @@ using Variant = ::std::variant<T...>;
#endif // __has_include
#endif // GTEST_HAS_ABSL
+#ifndef GTEST_INTERNAL_HAS_VARIANT
+#define GTEST_INTERNAL_HAS_VARIANT 0
+#endif
+
+#if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \
+ GTEST_INTERNAL_CPLUSPLUS_LANG < 201703L
+#define GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL 1
+#endif
+
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h
index cca2e1f..7c05b58 100644
--- a/googletest/include/gtest/internal/gtest-string.h
+++ b/googletest/include/gtest/internal/gtest-string.h
@@ -51,6 +51,7 @@
#include <string.h>
#include <cstdint>
+#include <sstream>
#include <string>
#include "gtest/internal/gtest-port.h"
@@ -72,7 +73,7 @@ class GTEST_API_ String {
// memory using malloc().
static const char* CloneCString(const char* c_str);
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
// Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
// able to pass strings to Win32 APIs on CE we need to convert them
// to 'Unicode', UTF-16.
diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h
index 6bc02a7..17a470b 100644
--- a/googletest/include/gtest/internal/gtest-type-util.h
+++ b/googletest/include/gtest/internal/gtest-type-util.h
@@ -37,6 +37,10 @@
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
+#include <string>
+#include <type_traits>
+#include <typeinfo>
+
#include "gtest/internal/gtest-port.h"
// #ifdef __GNUC__ is too general here. It is possible to use gcc without using
diff --git a/googletest/samples/prime_tables.h b/googletest/samples/prime_tables.h
index 7c0286e..08ad949 100644
--- a/googletest/samples/prime_tables.h
+++ b/googletest/samples/prime_tables.h
@@ -78,8 +78,9 @@ class PreCalculatedPrimeTable : public PrimeTable {
public:
// 'max' specifies the maximum number the prime table holds.
explicit PreCalculatedPrimeTable(int max)
- : is_prime_size_(max + 1), is_prime_(new bool[max + 1]) {
- CalculatePrimesUpTo(max);
+ : is_prime_size_(std::max(1, max + 1)),
+ is_prime_(new bool[static_cast<size_t>(is_prime_size_)]) {
+ CalculatePrimesUpTo(is_prime_size_ - 1);
}
~PreCalculatedPrimeTable() override { delete[] is_prime_; }
diff --git a/googletest/samples/sample10_unittest.cc b/googletest/samples/sample10_unittest.cc
index 95b4811..2107954 100644
--- a/googletest/samples/sample10_unittest.cc
+++ b/googletest/samples/sample10_unittest.cc
@@ -38,7 +38,6 @@ using ::testing::InitGoogleTest;
using ::testing::Test;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
-using ::testing::TestPartResult;
using ::testing::UnitTest;
namespace {
diff --git a/googletest/samples/sample9_unittest.cc b/googletest/samples/sample9_unittest.cc
index d627ea7..0a2f097 100644
--- a/googletest/samples/sample9_unittest.cc
+++ b/googletest/samples/sample9_unittest.cc
@@ -40,7 +40,6 @@ using ::testing::Test;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
using ::testing::TestPartResult;
-using ::testing::TestSuite;
using ::testing::UnitTest;
namespace {
// Provides alternative output mode which produces minimal amount of
diff --git a/googletest/src/gtest-assertion-result.cc b/googletest/src/gtest-assertion-result.cc
index f1c0b10..3998921 100644
--- a/googletest/src/gtest-assertion-result.cc
+++ b/googletest/src/gtest-assertion-result.cc
@@ -44,7 +44,7 @@ namespace testing {
// Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult::AssertionResult(const AssertionResult& other)
: success_(other.success_),
- message_(other.message_.get() != nullptr
+ message_(other.message_ != nullptr
? new ::std::string(*other.message_)
: static_cast< ::std::string*>(nullptr)) {}
@@ -58,7 +58,7 @@ void AssertionResult::swap(AssertionResult& other) {
// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
AssertionResult AssertionResult::operator!() const {
AssertionResult negation(!success_);
- if (message_.get() != nullptr) negation << *message_;
+ if (message_ != nullptr) negation << *message_;
return negation;
}
diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc
index b6968a9..0b87ba5 100644
--- a/googletest/src/gtest-death-test.cc
+++ b/googletest/src/gtest-death-test.cc
@@ -33,14 +33,16 @@
#include "gtest/gtest-death-test.h"
#include <functional>
+#include <memory>
#include <utility>
+#include <vector>
#include "gtest/internal/custom/gtest.h"
#include "gtest/internal/gtest-port.h"
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
-#if GTEST_OS_MAC
+#ifdef GTEST_OS_MAC
#include <crt_externs.h>
#endif // GTEST_OS_MAC
@@ -48,24 +50,24 @@
#include <fcntl.h>
#include <limits.h>
-#if GTEST_OS_LINUX
+#ifdef GTEST_OS_LINUX
#include <signal.h>
#endif // GTEST_OS_LINUX
#include <stdarg.h>
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
#include <windows.h>
#else
#include <sys/mman.h>
#include <sys/wait.h>
#endif // GTEST_OS_WINDOWS
-#if GTEST_OS_QNX
+#ifdef GTEST_OS_QNX
#include <spawn.h>
#endif // GTEST_OS_QNX
-#if GTEST_OS_FUCHSIA
+#ifdef GTEST_OS_FUCHSIA
#include <lib/fdio/fd.h>
#include <lib/fdio/io.h>
#include <lib/fdio/spawn.h>
@@ -131,13 +133,13 @@ GTEST_DEFINE_string_(
namespace testing {
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
namespace internal {
// Valid only for fast death tests. Indicates the code is running in the
// child process of a fast style death test.
-#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
+#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)
static bool g_in_fast_death_test_child = false;
#endif
@@ -147,7 +149,7 @@ static bool g_in_fast_death_test_child = false;
// tests. IMPORTANT: This is an internal utility. Using it may break the
// implementation of death tests. User code MUST NOT use it.
bool InDeathTestChild() {
-#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)
// On Windows and Fuchsia, death tests are thread-safe regardless of the value
// of the death_test_style flag.
@@ -169,7 +171,7 @@ ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {}
// ExitedWithCode function-call operator.
bool ExitedWithCode::operator()(int exit_status) const {
-#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)
return exit_status == exit_code_;
@@ -180,7 +182,7 @@ bool ExitedWithCode::operator()(int exit_status) const {
#endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
}
-#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
+#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)
// KilledBySignal constructor.
KilledBySignal::KilledBySignal(int signum) : signum_(signum) {}
@@ -207,7 +209,7 @@ namespace internal {
static std::string ExitSummary(int exit_code) {
Message m;
-#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)
m << "Exited with exit status " << exit_code;
@@ -234,7 +236,7 @@ bool ExitedUnsuccessfully(int exit_status) {
return !ExitedWithCode(0)(exit_status);
}
-#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
+#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)
// Generates a textual failure message when a death test finds more than
// one thread running, or cannot determine the number of threads, prior
// to executing the given statement. It is the responsibility of the
@@ -263,7 +265,7 @@ static const char kDeathTestReturned = 'R';
static const char kDeathTestThrew = 'T';
static const char kDeathTestInternalError = 'I';
-#if GTEST_OS_FUCHSIA
+#ifdef GTEST_OS_FUCHSIA
// File descriptor used for the pipe in the child process.
static const int kFuchsiaReadPipeFd = 3;
@@ -621,7 +623,18 @@ bool DeathTestImpl::Passed(bool status_ok) {
return success;
}
-#if GTEST_OS_WINDOWS
+// Note: The return value points into args, so the return value's lifetime is
+// bound to that of args.
+std::unique_ptr<char*[]> CreateArgvFromArgs(std::vector<std::string>& args) {
+ auto result = std::make_unique<char*[]>(args.size() + 1);
+ for (size_t i = 0; i < args.size(); ++i) {
+ result[i] = &args[i][0];
+ }
+ result[args.size()] = nullptr; // extra null terminator
+ return result;
+}
+
+#ifdef GTEST_OS_WINDOWS
// WindowsDeathTest implements death tests on Windows. Due to the
// specifics of starting new processes on Windows, death tests there are
// always threadsafe, and Google Test considers the
@@ -808,7 +821,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
return OVERSEE_TEST;
}
-#elif GTEST_OS_FUCHSIA
+#elif defined(GTEST_OS_FUCHSIA)
class FuchsiaDeathTest : public DeathTestImpl {
public:
@@ -836,36 +849,6 @@ class FuchsiaDeathTest : public DeathTestImpl {
zx::socket stderr_socket_;
};
-// Utility class for accumulating command-line arguments.
-class Arguments {
- public:
- Arguments() { args_.push_back(nullptr); }
-
- ~Arguments() {
- for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
- ++i) {
- free(*i);
- }
- }
- void AddArgument(const char* argument) {
- args_.insert(args_.end() - 1, posix::StrDup(argument));
- }
-
- template <typename Str>
- void AddArguments(const ::std::vector<Str>& arguments) {
- for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
- i != arguments.end(); ++i) {
- args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
- }
- }
- char* const* Argv() { return &args_[0]; }
-
- int size() { return static_cast<int>(args_.size()) - 1; }
-
- private:
- std::vector<char*> args_;
-};
-
// Waits for the child in a death test to exit, returning its exit
// status, or 0 if no child process exists. As a side effect, sets the
// outcome data member.
@@ -986,10 +969,10 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
kInternalRunDeathTestFlag + "=" + file_ +
"|" + StreamableToString(line_) + "|" +
StreamableToString(death_test_index);
- Arguments args;
- args.AddArguments(GetInjectableArgvs());
- args.AddArgument(filter_flag.c_str());
- args.AddArgument(internal_flag.c_str());
+
+ std::vector<std::string> args = GetInjectableArgvs();
+ args.push_back(filter_flag);
+ args.push_back(internal_flag);
// Build the pipe for communication with the child.
zx_status_t status;
@@ -1041,8 +1024,14 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
// Spawn the child process.
- status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0],
- args.Argv(), nullptr, 2, spawn_actions,
+ // Note: The test component must have `fuchsia.process.Launcher` declared
+ // in its manifest. (Fuchsia integration tests require creating a
+ // "Fuchsia Test Component" which contains a "Fuchsia Component Manifest")
+ // Launching processes is a privileged operation in Fuschia, and the
+ // declaration indicates that the ability is required for the component.
+ std::unique_ptr<char*[]> argv = CreateArgvFromArgs(args);
+ status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, argv[0], argv.get(),
+ nullptr, 2, spawn_actions,
child_process_.reset_and_get_address(), nullptr);
GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
@@ -1173,34 +1162,6 @@ class ExecDeathTest : public ForkingDeathTest {
const int line_;
};
-// Utility class for accumulating command-line arguments.
-class Arguments {
- public:
- Arguments() { args_.push_back(nullptr); }
-
- ~Arguments() {
- for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
- ++i) {
- free(*i);
- }
- }
- void AddArgument(const char* argument) {
- args_.insert(args_.end() - 1, posix::StrDup(argument));
- }
-
- template <typename Str>
- void AddArguments(const ::std::vector<Str>& arguments) {
- for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
- i != arguments.end(); ++i) {
- args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
- }
- }
- char* const* Argv() { return &args_[0]; }
-
- private:
- std::vector<char*> args_;
-};
-
// A struct that encompasses the arguments to the child process of a
// threadsafe-style death test process.
struct ExecDeathTestArgs {
@@ -1208,7 +1169,7 @@ struct ExecDeathTestArgs {
int close_fd; // File descriptor to close; the read end of a pipe
};
-#if GTEST_OS_QNX
+#ifdef GTEST_OS_QNX
extern "C" char** environ;
#else // GTEST_OS_QNX
// The main function for a threadsafe-style death test child process.
@@ -1289,7 +1250,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
ExecDeathTestArgs args = {argv, close_fd};
pid_t child_pid = -1;
-#if GTEST_OS_QNX
+#ifdef GTEST_OS_QNX
// Obtains the current directory and sets it to be closed in the child
// process.
const int cwd_fd = open(".", O_RDONLY);
@@ -1320,7 +1281,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
#else // GTEST_OS_QNX
-#if GTEST_OS_LINUX
+#ifdef GTEST_OS_LINUX
// When a SIGPROF signal is received while fork() or clone() are executing,
// the process may hang. To avoid this, we ignore SIGPROF here and re-enable
// it after the call to fork()/clone() is complete.
@@ -1367,11 +1328,10 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
#endif // GTEST_HAS_CLONE
if (use_fork && (child_pid = fork()) == 0) {
- ExecDeathTestChildMain(&args);
- _exit(0);
+ _exit(ExecDeathTestChildMain(&args));
}
#endif // GTEST_OS_QNX
-#if GTEST_OS_LINUX
+#ifdef GTEST_OS_LINUX
GTEST_DEATH_TEST_CHECK_SYSCALL_(
sigaction(SIGPROF, &saved_sigprof_action, nullptr));
#endif // GTEST_OS_LINUX
@@ -1410,10 +1370,9 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() {
StreamableToString(line_) + "|" +
StreamableToString(death_test_index) + "|" +
StreamableToString(pipe_fd[1]);
- Arguments args;
- args.AddArguments(GetArgvsForDeathTestChildProcess());
- args.AddArgument(filter_flag.c_str());
- args.AddArgument(internal_flag.c_str());
+ std::vector<std::string> args = GetArgvsForDeathTestChildProcess();
+ args.push_back(filter_flag);
+ args.push_back(internal_flag);
DeathTest::set_last_death_test_message("");
@@ -1422,7 +1381,8 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() {
// is necessary.
FlushInfoLog();
- const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
+ std::unique_ptr<char*[]> argv = CreateArgvFromArgs(args);
+ const pid_t child_pid = ExecDeathTestSpawnChild(argv.get(), pipe_fd[0]);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
set_child_pid(child_pid);
set_read_fd(pipe_fd[0]);
@@ -1463,14 +1423,14 @@ bool DefaultDeathTestFactory::Create(const char* statement,
}
}
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
if (GTEST_FLAG_GET(death_test_style) == "threadsafe" ||
GTEST_FLAG_GET(death_test_style) == "fast") {
*test = new WindowsDeathTest(statement, std::move(matcher), file, line);
}
-#elif GTEST_OS_FUCHSIA
+#elif defined(GTEST_OS_FUCHSIA)
if (GTEST_FLAG_GET(death_test_style) == "threadsafe" ||
GTEST_FLAG_GET(death_test_style) == "fast") {
@@ -1497,7 +1457,7 @@ bool DefaultDeathTestFactory::Create(const char* statement,
return true;
}
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Recreates the pipe and event handles from the provided parameters,
// signals the event, and returns a file descriptor wrapped around the pipe
// handle. This function is called in the child process only.
@@ -1564,7 +1524,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id,
// initialized from the GTEST_FLAG(internal_run_death_test) flag if
// the flag is specified; otherwise returns NULL.
InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
- if (GTEST_FLAG_GET(internal_run_death_test) == "") return nullptr;
+ if (GTEST_FLAG_GET(internal_run_death_test).empty()) return nullptr;
// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
// can use it here.
@@ -1574,7 +1534,7 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
SplitString(GTEST_FLAG_GET(internal_run_death_test), '|', &fields);
int write_fd = -1;
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
unsigned int parent_process_id = 0;
size_t write_handle_as_size_t = 0;
@@ -1591,7 +1551,7 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t,
event_handle_as_size_t);
-#elif GTEST_OS_FUCHSIA
+#elif defined(GTEST_OS_FUCHSIA)
if (fields.size() != 3 || !ParseNaturalNumber(fields[1], &line) ||
!ParseNaturalNumber(fields[2], &index)) {
diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc
index f6ee90c..48dee13 100644
--- a/googletest/src/gtest-filepath.cc
+++ b/googletest/src/gtest-filepath.cc
@@ -34,9 +34,9 @@
#include "gtest/gtest-message.h"
#include "gtest/internal/gtest-port.h"
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
#include <windows.h>
-#elif GTEST_OS_WINDOWS
+#elif defined(GTEST_OS_WINDOWS)
#include <direct.h>
#include <io.h>
#else
@@ -47,7 +47,7 @@
#include "gtest/internal/gtest-string.h"
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
#define GTEST_PATH_MAX_ _MAX_PATH
#elif defined(PATH_MAX)
#define GTEST_PATH_MAX_ PATH_MAX
@@ -57,10 +57,12 @@
#define GTEST_PATH_MAX_ _POSIX_PATH_MAX
#endif // GTEST_OS_WINDOWS
+#if GTEST_HAS_FILE_SYSTEM
+
namespace testing {
namespace internal {
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// On Windows, '\\' is the standard path separator, but many tools and the
// Windows API also accept '/' as an alternate path separator. Unless otherwise
// noted, a file path can contain either kind of path separators, or a mixture
@@ -68,7 +70,7 @@ namespace internal {
const char kPathSeparator = '\\';
const char kAlternatePathSeparator = '/';
const char kAlternatePathSeparatorString[] = "/";
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
// Windows CE doesn't have a current directory. You should not use
// the current directory in tests on Windows CE, but this at least
// provides a reasonable fallback.
@@ -94,19 +96,20 @@ static bool IsPathSeparator(char c) {
// Returns the current working directory, or "" if unsuccessful.
FilePath FilePath::GetCurrentDir() {
-#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
- GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \
- GTEST_OS_XTENSA
+#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \
+ defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_ESP8266) || \
+ defined(GTEST_OS_ESP32) || defined(GTEST_OS_XTENSA) || \
+ defined(GTEST_OS_QURT)
// These platforms do not have a current directory, so we just return
// something reasonable.
return FilePath(kCurrentDirectoryString);
-#elif GTEST_OS_WINDOWS
+#elif defined(GTEST_OS_WINDOWS)
char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
#else
char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
char* result = getcwd(cwd, sizeof(cwd));
-#if GTEST_OS_NACL
+#ifdef GTEST_OS_NACL
// getcwd will likely fail in NaCl due to the sandbox, so return something
// reasonable. The user may have provided a shim implementation for getcwd,
// however, so fallback only when failure is detected.
@@ -145,6 +148,44 @@ const char* FilePath::FindLastPathSeparator() const {
return last_sep;
}
+size_t FilePath::CalculateRootLength() const {
+ const auto& path = pathname_;
+ auto s = path.begin();
+ auto end = path.end();
+#ifdef GTEST_OS_WINDOWS
+ if (end - s >= 2 && s[1] == ':' && (end - s == 2 || IsPathSeparator(s[2])) &&
+ (('A' <= s[0] && s[0] <= 'Z') || ('a' <= s[0] && s[0] <= 'z'))) {
+ // A typical absolute path like "C:\Windows" or "D:"
+ s += 2;
+ if (s != end) {
+ ++s;
+ }
+ } else if (end - s >= 3 && IsPathSeparator(*s) && IsPathSeparator(*(s + 1)) &&
+ !IsPathSeparator(*(s + 2))) {
+ // Move past the "\\" prefix in a UNC path like "\\Server\Share\Folder"
+ s += 2;
+ // Skip 2 components and their following separators ("Server\" and "Share\")
+ for (int i = 0; i < 2; ++i) {
+ while (s != end) {
+ bool stop = IsPathSeparator(*s);
+ ++s;
+ if (stop) {
+ break;
+ }
+ }
+ }
+ } else if (s != end && IsPathSeparator(*s)) {
+ // A drive-rooted path like "\Windows"
+ ++s;
+ }
+#else
+ if (s != end && IsPathSeparator(*s)) {
+ ++s;
+ }
+#endif
+ return static_cast<size_t>(s - path.begin());
+}
+
// Returns a copy of the FilePath with the directory part removed.
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
@@ -204,7 +245,7 @@ FilePath FilePath::ConcatPaths(const FilePath& directory,
// Returns true if pathname describes something findable in the file-system,
// either a file, directory, or whatever.
bool FilePath::FileOrDirectoryExists() const {
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
const DWORD attributes = GetFileAttributes(unicode);
delete[] unicode;
@@ -219,7 +260,7 @@ bool FilePath::FileOrDirectoryExists() const {
// that exists.
bool FilePath::DirectoryExists() const {
bool result = false;
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Don't strip off trailing separator if path is a root directory on
// Windows (like "C:\\").
const FilePath& path(IsRootDirectory() ? *this
@@ -228,7 +269,7 @@ bool FilePath::DirectoryExists() const {
const FilePath& path(*this);
#endif
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
const DWORD attributes = GetFileAttributes(unicode);
delete[] unicode;
@@ -246,27 +287,15 @@ bool FilePath::DirectoryExists() const {
}
// Returns true if pathname describes a root directory. (Windows has one
-// root directory per disk drive.)
+// root directory per disk drive. UNC share roots are also included.)
bool FilePath::IsRootDirectory() const {
-#if GTEST_OS_WINDOWS
- return pathname_.length() == 3 && IsAbsolutePath();
-#else
- return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
-#endif
+ size_t root_length = CalculateRootLength();
+ return root_length > 0 && root_length == pathname_.size() &&
+ IsPathSeparator(pathname_[root_length - 1]);
}
// Returns true if pathname describes an absolute path.
-bool FilePath::IsAbsolutePath() const {
- const char* const name = pathname_.c_str();
-#if GTEST_OS_WINDOWS
- return pathname_.length() >= 3 &&
- ((name[0] >= 'a' && name[0] <= 'z') ||
- (name[0] >= 'A' && name[0] <= 'Z')) &&
- name[1] == ':' && IsPathSeparator(name[2]);
-#else
- return IsPathSeparator(name[0]);
-#endif
-}
+bool FilePath::IsAbsolutePath() const { return CalculateRootLength() > 0; }
// Returns a pathname for a file that does not currently exist. The pathname
// will be directory/base_name.extension or
@@ -316,14 +345,15 @@ bool FilePath::CreateDirectoriesRecursively() const {
// directory for any reason, including if the parent directory does not
// exist. Not named "CreateDirectory" because that's a macro on Windows.
bool FilePath::CreateFolder() const {
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
FilePath removed_sep(this->RemoveTrailingPathSeparator());
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
delete[] unicode;
-#elif GTEST_OS_WINDOWS
+#elif defined(GTEST_OS_WINDOWS)
int result = _mkdir(pathname_.c_str());
-#elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA
+#elif defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \
+ defined(GTEST_OS_QURT)
// do nothing
int result = 0;
#else
@@ -347,17 +377,27 @@ 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 "..".
+// Note that "\\Host\Share" does not contain a redundancy on Windows!
void FilePath::Normalize() {
auto out = pathname_.begin();
- for (const char character : pathname_) {
+ auto i = pathname_.cbegin();
+#ifdef GTEST_OS_WINDOWS
+ // UNC paths are treated specially
+ if (pathname_.end() - i >= 3 && IsPathSeparator(*i) &&
+ IsPathSeparator(*(i + 1)) && !IsPathSeparator(*(i + 2))) {
+ *(out++) = kPathSeparator;
+ *(out++) = kPathSeparator;
+ }
+#endif
+ while (i != pathname_.end()) {
+ const char character = *i;
if (!IsPathSeparator(character)) {
*(out++) = character;
} else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {
*(out++) = kPathSeparator;
- } else {
- continue;
}
+ ++i;
}
pathname_.erase(out, pathname_.end());
@@ -365,3 +405,5 @@ void FilePath::Normalize() {
} // namespace internal
} // namespace testing
+
+#endif // GTEST_HAS_FILE_SYSTEM
diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h
index 8c650e0..16841b5 100644
--- a/googletest/src/gtest-internal-inl.h
+++ b/googletest/src/gtest-internal-inl.h
@@ -44,6 +44,7 @@
#include <algorithm>
#include <cstdint>
#include <memory>
+#include <set>
#include <string>
#include <vector>
@@ -54,7 +55,7 @@
#include <netdb.h> // NOLINT
#endif
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
#include <windows.h> // NOLINT
#endif // GTEST_OS_WINDOWS
@@ -91,7 +92,8 @@ GTEST_API_ TimeInMillis GetTimeInMillis();
// Returns true if and only if Google Test should use colors in the output.
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
-// Formats the given time in milliseconds as seconds.
+// Formats the given time in milliseconds as seconds. If the input is an exact N
+// seconds, the output has a trailing decimal point (e.g., "N." intead of "N").
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
// Converts the given time in milliseconds to a date string in the ISO 8601
@@ -212,7 +214,7 @@ class GTestFlagSaver {
int32_t stack_trace_depth_;
std::string stream_result_to_;
bool throw_on_failure_;
-} GTEST_ATTRIBUTE_UNUSED_;
+};
// Converts a Unicode code point to a narrow string in UTF-8 encoding.
// code_point parameter is of type UInt32 because wchar_t may not be
@@ -382,7 +384,7 @@ class GTEST_API_ UnitTestOptions {
static bool FilterMatchesTest(const std::string& test_suite_name,
const std::string& test_name);
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Function for supporting the gtest_catch_exception flag.
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
@@ -396,9 +398,11 @@ class GTEST_API_ UnitTestOptions {
static bool MatchesFilter(const std::string& name, const char* filter);
};
+#if GTEST_HAS_FILE_SYSTEM
// Returns the current application's name, removing directory path if that
// is present. Used by UnitTestOptions::GetOutputFile.
GTEST_API_ FilePath GetCurrentExecutableName();
+#endif // GTEST_HAS_FILE_SYSTEM
// The role interface for getting the OS stack trace as a string.
class OsStackTraceGetterInterface {
@@ -438,7 +442,7 @@ class OsStackTraceGetter : public OsStackTraceGetterInterface {
void UponLeavingGTest() override;
private:
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
Mutex mutex_; // Protects all internal state.
// We save the stack frame below the frame that calls user code.
@@ -668,7 +672,7 @@ class GTEST_API_ UnitTestImpl {
void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc,
TestInfo* test_info) {
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
// In order to support thread-safe death tests, we need to
// remember the original working directory when the test program
// was first invoked. We cannot do this in RUN_ALL_TESTS(), as
@@ -774,7 +778,7 @@ class GTEST_API_ UnitTestImpl {
return gtest_trace_stack_.get();
}
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
void InitDeathTestSubprocessControlInfo() {
internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
}
@@ -840,9 +844,11 @@ class GTEST_API_ UnitTestImpl {
// The UnitTest object that owns this implementation object.
UnitTest* const parent_;
+#if GTEST_HAS_FILE_SYSTEM
// The working directory when the first TEST() or TEST_F() was
// executed.
internal::FilePath original_working_dir_;
+#endif // GTEST_HAS_FILE_SYSTEM
// The default test part result reporters.
DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
@@ -937,7 +943,7 @@ class GTEST_API_ UnitTestImpl {
// How long the test took to run, in milliseconds.
TimeInMillis elapsed_time_;
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
// The decomposed components of the gtest_internal_run_death_test flag,
// parsed when RUN_ALL_TESTS is called.
std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
@@ -961,7 +967,7 @@ inline UnitTestImpl* GetUnitTestImpl() {
return UnitTest::GetInstance()->impl();
}
-#if GTEST_USES_SIMPLE_RE
+#ifdef GTEST_USES_SIMPLE_RE
// Internal helper functions for implementing the simple regular
// expression matcher.
@@ -987,7 +993,7 @@ GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
// Returns the message describing the last system error, regardless of the
// platform.
diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc
index d797fe4..994fabd 100644
--- a/googletest/src/gtest-port.cc
+++ b/googletest/src/gtest-port.cc
@@ -38,7 +38,7 @@
#include <fstream>
#include <memory>
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
#include <io.h>
#include <sys/stat.h>
#include <windows.h>
@@ -51,32 +51,34 @@
#include <unistd.h>
#endif // GTEST_OS_WINDOWS
-#if GTEST_OS_MAC
+#ifdef GTEST_OS_MAC
#include <mach/mach_init.h>
#include <mach/task.h>
#include <mach/vm_map.h>
#endif // GTEST_OS_MAC
-#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
- GTEST_OS_NETBSD || GTEST_OS_OPENBSD
+#if defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
+ defined(GTEST_OS_GNU_KFREEBSD) || defined(GTEST_OS_NETBSD) || \
+ defined(GTEST_OS_OPENBSD)
#include <sys/sysctl.h>
-#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
+#if defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
+ defined(GTEST_OS_GNU_KFREEBSD)
#include <sys/user.h>
#endif
#endif
-#if GTEST_OS_QNX
+#ifdef GTEST_OS_QNX
#include <devctl.h>
#include <fcntl.h>
#include <sys/procfs.h>
#endif // GTEST_OS_QNX
-#if GTEST_OS_AIX
+#ifdef GTEST_OS_AIX
#include <procinfo.h>
#include <sys/types.h>
#endif // GTEST_OS_AIX
-#if GTEST_OS_FUCHSIA
+#ifdef GTEST_OS_FUCHSIA
#include <zircon/process.h>
#include <zircon/syscalls.h>
#endif // GTEST_OS_FUCHSIA
@@ -90,7 +92,7 @@
namespace testing {
namespace internal {
-#if GTEST_OS_LINUX || GTEST_OS_GNU_HURD
+#if defined(GTEST_OS_LINUX) || defined(GTEST_OS_GNU_HURD)
namespace {
template <typename T>
@@ -113,7 +115,7 @@ size_t GetThreadCount() {
return ReadProcFileField<size_t>(filename, 19);
}
-#elif GTEST_OS_MAC
+#elif defined(GTEST_OS_MAC)
size_t GetThreadCount() {
const task_t task = mach_task_self();
@@ -131,20 +133,20 @@ size_t GetThreadCount() {
}
}
-#elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
- GTEST_OS_NETBSD
+#elif defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
+ defined(GTEST_OS_GNU_KFREEBSD) || defined(GTEST_OS_NETBSD)
-#if GTEST_OS_NETBSD
+#ifdef GTEST_OS_NETBSD
#undef KERN_PROC
#define KERN_PROC KERN_PROC2
#define kinfo_proc kinfo_proc2
#endif
-#if GTEST_OS_DRAGONFLY
+#ifdef GTEST_OS_DRAGONFLY
#define KP_NLWP(kp) (kp.kp_nthreads)
-#elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
+#elif defined(GTEST_OS_FREEBSD) || defined(GTEST_OS_GNU_KFREEBSD)
#define KP_NLWP(kp) (kp.ki_numthreads)
-#elif GTEST_OS_NETBSD
+#elif defined(GTEST_OS_NETBSD)
#define KP_NLWP(kp) (kp.p_nlwps)
#endif
@@ -156,7 +158,7 @@ size_t GetThreadCount() {
KERN_PROC,
KERN_PROC_PID,
getpid(),
-#if GTEST_OS_NETBSD
+#ifdef GTEST_OS_NETBSD
sizeof(struct kinfo_proc),
1,
#endif
@@ -169,7 +171,7 @@ size_t GetThreadCount() {
}
return static_cast<size_t>(KP_NLWP(info));
}
-#elif GTEST_OS_OPENBSD
+#elif defined(GTEST_OS_OPENBSD)
// Returns the number of threads running in the process, or 0 to indicate that
// we cannot detect it.
@@ -206,7 +208,7 @@ size_t GetThreadCount() {
return nthreads;
}
-#elif GTEST_OS_QNX
+#elif defined(GTEST_OS_QNX)
// Returns the number of threads running in the process, or 0 to indicate that
// we cannot detect it.
@@ -226,7 +228,7 @@ size_t GetThreadCount() {
}
}
-#elif GTEST_OS_AIX
+#elif defined(GTEST_OS_AIX)
size_t GetThreadCount() {
struct procentry64 entry;
@@ -239,7 +241,7 @@ size_t GetThreadCount() {
}
}
-#elif GTEST_OS_FUCHSIA
+#elif defined(GTEST_OS_FUCHSIA)
size_t GetThreadCount() {
int dummy_buffer;
@@ -264,7 +266,7 @@ size_t GetThreadCount() {
#endif // GTEST_OS_LINUX
-#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
+#if defined(GTEST_IS_THREADSAFE) && defined(GTEST_OS_WINDOWS)
AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
@@ -655,7 +657,7 @@ void ThreadLocalRegistry::OnThreadLocalDestroyed(
#endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
-#if GTEST_USES_POSIX_RE
+#ifdef GTEST_USES_POSIX_RE
// Implements RE. Currently only needed for death tests.
@@ -668,7 +670,6 @@ RE::~RE() {
regfree(&partial_regex_);
regfree(&full_regex_);
}
- free(const_cast<char*>(pattern_));
}
// Returns true if and only if regular expression re matches the entire str.
@@ -690,7 +691,7 @@ bool RE::PartialMatch(const char* str, const RE& re) {
// Initializes an RE from its string representation.
void RE::Init(const char* regex) {
- pattern_ = posix::StrDup(regex);
+ pattern_ = regex;
// Reserves enough bytes to hold the regular expression used for a
// full match.
@@ -718,7 +719,7 @@ void RE::Init(const char* regex) {
delete[] full_pattern;
}
-#elif GTEST_USES_SIMPLE_RE
+#elif defined(GTEST_USES_SIMPLE_RE)
// Returns true if and only if ch appears anywhere in str (excluding the
// terminating '\0' character).
@@ -920,27 +921,26 @@ bool MatchRegexAnywhere(const char* regex, const char* str) {
// Implements the RE class.
-RE::~RE() {
- free(const_cast<char*>(pattern_));
- free(const_cast<char*>(full_pattern_));
-}
+RE::~RE() = default;
// Returns true if and only if regular expression re matches the entire str.
bool RE::FullMatch(const char* str, const RE& re) {
- return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
+ return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_.c_str(), str);
}
// Returns true if and only if regular expression re matches a substring of
// str (including str itself).
bool RE::PartialMatch(const char* str, const RE& re) {
- return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
+ return re.is_valid_ && MatchRegexAnywhere(re.pattern_.c_str(), str);
}
// Initializes an RE from its string representation.
void RE::Init(const char* regex) {
- pattern_ = full_pattern_ = nullptr;
+ full_pattern_.clear();
+ pattern_.clear();
+
if (regex != nullptr) {
- pattern_ = posix::StrDup(regex);
+ pattern_ = regex;
}
is_valid_ = ValidateRegex(regex);
@@ -949,25 +949,19 @@ void RE::Init(const char* regex) {
return;
}
- const size_t len = strlen(regex);
// Reserves enough bytes to hold the regular expression used for a
- // full match: we need space to prepend a '^', append a '$', and
- // terminate the string with '\0'.
- char* buffer = static_cast<char*>(malloc(len + 3));
- full_pattern_ = buffer;
+ // full match: we need space to prepend a '^' and append a '$'.
+ full_pattern_.reserve(pattern_.size() + 2);
- if (*regex != '^')
- *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
-
- // We don't use snprintf or strncpy, as they trigger a warning when
- // compiled with VC++ 8.0.
- memcpy(buffer, regex, len);
- buffer += len;
+ if (pattern_.empty() || pattern_.front() != '^') {
+ full_pattern_.push_back('^'); // Makes sure full_pattern_ starts with '^'.
+ }
- if (len == 0 || regex[len - 1] != '$')
- *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
+ full_pattern_.append(pattern_);
- *buffer = '\0';
+ if (pattern_.empty() || pattern_.back() != '$') {
+ full_pattern_.push_back('$'); // Makes sure full_pattern_ ends with '$'.
+ }
}
#endif // GTEST_USES_POSIX_RE
@@ -1035,7 +1029,7 @@ class CapturedStream {
public:
// The ctor redirects the stream to a temporary file.
explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
char temp_dir_path[MAX_PATH + 1] = {'\0'}; // NOLINT
char temp_file_path[MAX_PATH + 1] = {'\0'}; // NOLINT
@@ -1054,7 +1048,7 @@ class CapturedStream {
// directory, so we create the temporary file in a temporary directory.
std::string name_template;
-#if GTEST_OS_LINUX_ANDROID
+#ifdef GTEST_OS_LINUX_ANDROID
// Note: Android applications are expected to call the framework's
// Context.getExternalStorageDirectory() method through JNI to get
// the location of the world-writable SD Card directory. However,
@@ -1067,7 +1061,7 @@ class CapturedStream {
// '/sdcard' and other variants cannot be relied on, as they are not
// guaranteed to be mounted, or may have a delay in mounting.
name_template = "/data/local/tmp/";
-#elif GTEST_OS_IOS
+#elif defined(GTEST_OS_IOS)
char user_temp_dir[PATH_MAX + 1];
// Documented alternative to NSTemporaryDirectory() (for obtaining creating
@@ -1227,7 +1221,7 @@ std::string ReadEntireFile(FILE* file) {
return content;
}
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
static const std::vector<std::string>* g_injected_test_argvs =
nullptr; // Owned.
@@ -1254,7 +1248,7 @@ void ClearInjectableArgvs() {
}
#endif // GTEST_HAS_DEATH_TEST
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
namespace posix {
void Abort() {
DebugBreak();
diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc
index d475ad3..de740e7 100644
--- a/googletest/src/gtest-printers.cc
+++ b/googletest/src/gtest-printers.cc
@@ -528,7 +528,7 @@ void PrintStringTo(const ::std::string& s, ostream* os) {
}
}
-#ifdef __cpp_char8_t
+#ifdef __cpp_lib_char8_t
void PrintU8StringTo(const ::std::u8string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
diff --git a/googletest/src/gtest-test-part.cc b/googletest/src/gtest-test-part.cc
index eb7c8d1..df677e6 100644
--- a/googletest/src/gtest-test-part.cc
+++ b/googletest/src/gtest-test-part.cc
@@ -37,8 +37,6 @@
namespace testing {
-using internal::GetUnitTestImpl;
-
// Gets the summary of the failure message by omitting the stack trace
// in it.
std::string TestPartResult::ExtractSummary(const char* message) {
diff --git a/googletest/src/gtest-typed-test.cc b/googletest/src/gtest-typed-test.cc
index a2828b8..9941306 100644
--- a/googletest/src/gtest-typed-test.cc
+++ b/googletest/src/gtest-typed-test.cc
@@ -90,7 +90,7 @@ const char* TypedTestSuitePState::VerifyRegisteredTestNames(
}
const std::string& errors_str = errors.GetString();
- if (errors_str != "") {
+ if (!errors_str.empty()) {
fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
errors_str.c_str());
fflush(stderr);
diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc
index 81409a3..15cee3f 100644
--- a/googletest/src/gtest.cc
+++ b/googletest/src/gtest.cc
@@ -44,8 +44,10 @@
#include <chrono> // NOLINT
#include <cmath>
#include <cstdint>
+#include <cstring>
#include <initializer_list>
#include <iomanip>
+#include <ios>
#include <iterator>
#include <limits>
#include <list>
@@ -58,8 +60,9 @@
#include "gtest/gtest-assertion-result.h"
#include "gtest/gtest-spi.h"
#include "gtest/internal/custom/gtest.h"
+#include "gtest/internal/gtest-port.h"
-#if GTEST_OS_LINUX
+#ifdef GTEST_OS_LINUX
#include <fcntl.h> // NOLINT
#include <limits.h> // NOLINT
@@ -72,18 +75,18 @@
#include <string>
-#elif GTEST_OS_ZOS
+#elif defined(GTEST_OS_ZOS)
#include <sys/time.h> // NOLINT
// On z/OS we additionally need strings.h for strcasecmp.
#include <strings.h> // NOLINT
-#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
+#elif defined(GTEST_OS_WINDOWS_MOBILE) // We are on Windows CE.
#include <windows.h> // NOLINT
#undef min
-#elif GTEST_OS_WINDOWS // We are on Windows proper.
+#elif defined(GTEST_OS_WINDOWS) // We are on Windows proper.
#include <windows.h> // NOLINT
#undef min
@@ -97,7 +100,7 @@
#include <sys/timeb.h> // NOLINT
#include <sys/types.h> // NOLINT
-#if GTEST_OS_WINDOWS_MINGW
+#ifdef GTEST_OS_WINDOWS_MINGW
#include <sys/time.h> // NOLINT
#endif // GTEST_OS_WINDOWS_MINGW
@@ -123,17 +126,17 @@
#include "src/gtest-internal-inl.h"
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
#define vsnprintf _vsnprintf
#endif // GTEST_OS_WINDOWS
-#if GTEST_OS_MAC
+#ifdef GTEST_OS_MAC
#ifndef GTEST_OS_IOS
#include <crt_externs.h>
#endif
#endif
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
#include "absl/debugging/failure_signal_handler.h"
#include "absl/debugging/stacktrace.h"
#include "absl/debugging/symbolize.h"
@@ -143,6 +146,14 @@
#include "absl/strings/str_replace.h"
#endif // GTEST_HAS_ABSL
+// Checks builtin compiler feature |x| while avoiding an extra layer of #ifdefs
+// at the callsite.
+#if defined(__has_builtin)
+#define GTEST_HAS_BUILTIN(x) __has_builtin(x)
+#else
+#define GTEST_HAS_BUILTIN(x) 0
+#endif // defined(__has_builtin)
+
namespace testing {
using internal::CountIf;
@@ -186,6 +197,7 @@ const char kStackTraceMarker[] = "\nStack trace:\n";
// is specified on the command line.
bool g_help_flag = false;
+#if GTEST_HAS_FILE_SYSTEM
// Utility function to Open File for Writing
static FILE* OpenFileForWriting(const std::string& output_file) {
FILE* fileout = nullptr;
@@ -200,6 +212,7 @@ static FILE* OpenFileForWriting(const std::string& output_file) {
}
return fileout;
}
+#endif // GTEST_HAS_FILE_SYSTEM
} // namespace internal
@@ -396,7 +409,7 @@ uint32_t Random::Generate(uint32_t range) {
// GTestIsInitialized() returns true if and only if the user has initialized
// Google Test. Useful for catching the user mistake of not initializing
// Google Test before calling RUN_ALL_TESTS().
-static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
+static bool GTestIsInitialized() { return !GetArgvs().empty(); }
// Iterates over a vector of TestSuites, keeping a running sum of the
// results of calling a given int-returning method on each.
@@ -612,12 +625,13 @@ static ::std::vector<std::string> g_argvs;
#endif // defined(GTEST_CUSTOM_GET_ARGVS_)
}
+#if GTEST_HAS_FILE_SYSTEM
// Returns the current application's name, removing directory path if that
// is present.
FilePath GetCurrentExecutableName() {
FilePath result;
-#if GTEST_OS_WINDOWS || GTEST_OS_OS2
+#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_OS2)
result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
#else
result.Set(FilePath(GetArgvs()[0]));
@@ -625,6 +639,7 @@ FilePath GetCurrentExecutableName() {
return result.RemoveDirectoryName();
}
+#endif // GTEST_HAS_FILE_SYSTEM
// Functions for processing the gtest_output flag.
@@ -639,6 +654,7 @@ std::string UnitTestOptions::GetOutputFormat() {
static_cast<size_t>(colon - gtest_output_flag));
}
+#if GTEST_HAS_FILE_SYSTEM
// Returns the name of the requested output file, or the default if none
// was explicitly specified.
std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
@@ -669,6 +685,7 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
GetOutputFormat().c_str()));
return result.string();
}
+#endif // GTEST_HAS_FILE_SYSTEM
// Returns true if and only if the wildcard pattern matches the string. Each
// pattern consists of regular characters, single-character wildcards (?), and
@@ -1115,17 +1132,24 @@ std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
// A helper class for measuring elapsed times.
class Timer {
public:
- Timer() : start_(std::chrono::steady_clock::now()) {}
+ Timer() : start_(clock::now()) {}
// Return time elapsed in milliseconds since the timer was created.
TimeInMillis Elapsed() {
- return std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now() - start_)
+ return std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() -
+ start_)
.count();
}
private:
- std::chrono::steady_clock::time_point start_;
+ // Fall back to the system_clock when building with newlib on a system
+ // without a monotonic clock.
+#if defined(_NEWLIB_VERSION) && !defined(CLOCK_MONOTONIC)
+ using clock = std::chrono::system_clock;
+#else
+ using clock = std::chrono::steady_clock;
+#endif
+ clock::time_point start_;
};
// Returns a timestamp as milliseconds since the epoch. Note this time may jump
@@ -1142,7 +1166,7 @@ TimeInMillis GetTimeInMillis() {
// class String.
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
// Creates a UTF-16 wide string from the given ANSI string, allocating
// memory using new. The caller is responsible for deleting the return
// value using delete[]. Returns the wide string, or NULL if the
@@ -1844,14 +1868,14 @@ AssertionResult IsNotSubstring(const char* needle_expr,
namespace internal {
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
namespace {
// Helper function for IsHRESULT{SuccessFailure} predicates
AssertionResult HRESULTFailureHelper(const char* expr, const char* expected,
long hr) { // NOLINT
-#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
+#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_TV_TITLE)
// Windows CE doesn't support FormatMessage.
const char error_text[] = "";
@@ -2112,9 +2136,9 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
if (rhs == nullptr) return false;
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
return _wcsicmp(lhs, rhs) == 0;
-#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
+#elif defined(GTEST_OS_LINUX) && !defined(GTEST_OS_LINUX_ANDROID)
return wcscasecmp(lhs, rhs) == 0;
#else
// Android, Mac OS X and Cygwin don't define wcscasecmp.
@@ -2302,7 +2326,9 @@ static std::vector<std::string> GetReservedAttributesForElement(
return std::vector<std::string>();
}
+#if GTEST_HAS_FILE_SYSTEM
// TODO(jdesprez): Merge the two getReserved attributes once skip is improved
+// This function is only used when file systems are enabled.
static std::vector<std::string> GetReservedOutputAttributesForElement(
const std::string& xml_element) {
if (xml_element == "testsuites") {
@@ -2317,6 +2343,7 @@ static std::vector<std::string> GetReservedOutputAttributesForElement(
// This code is unreachable but some compilers may not realizes that.
return std::vector<std::string>();
}
+#endif
static std::string FormatWordList(const std::vector<std::string>& words) {
Message word_list;
@@ -2437,13 +2464,6 @@ void Test::RecordProperty(const std::string& key, const std::string& value) {
UnitTest::GetInstance()->RecordProperty(key, value);
}
-// Allows user supplied key value pairs to be recorded for later output.
-void Test::RecordProperty(const std::string& key, int value) {
- Message value_message;
- value_message << value;
- RecordProperty(key, value_message.GetString().c_str());
-}
-
namespace internal {
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
@@ -2713,7 +2733,8 @@ TestInfo::TestInfo(const std::string& a_test_suite_name,
internal::TypeId fixture_class_id,
internal::TestFactoryBase* factory)
: test_suite_name_(a_test_suite_name),
- name_(a_name),
+ // begin()/end() is MSVC 17.3.3 ASAN crash workaround (GitHub issue #3997)
+ name_(a_name.begin(), a_name.end()),
type_param_(a_type_param ? new std::string(a_type_param) : nullptr),
value_param_(a_value_param ? new std::string(a_value_param) : nullptr),
location_(a_code_location),
@@ -2777,37 +2798,6 @@ void ReportInvalidTestSuiteType(const char* test_suite_name,
code_location.line)
<< " " << errors.GetString();
}
-} // namespace internal
-
-namespace {
-
-// A predicate that checks the test name of a TestInfo against a known
-// value.
-//
-// This is used for implementation of the TestSuite class only. We put
-// it in the anonymous namespace to prevent polluting the outer
-// namespace.
-//
-// TestNameIs is copyable.
-class TestNameIs {
- public:
- // Constructor.
- //
- // TestNameIs has NO default constructor.
- explicit TestNameIs(const char* name) : name_(name) {}
-
- // Returns true if and only if the test name of test_info matches name_.
- bool operator()(const TestInfo* test_info) const {
- return test_info && test_info->name() == name_;
- }
-
- private:
- std::string name_;
-};
-
-} // namespace
-
-namespace internal {
// This method expands all parameterized tests registered with macros TEST_P
// and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.
@@ -2992,6 +2982,25 @@ void TestSuite::Run() {
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
+ // Ensure our tests are in a deterministic order.
+ //
+ // We do this by sorting lexicographically on (file, line number), providing
+ // an order matching what the user can see in the source code.
+ //
+ // In the common case the line number comparison shouldn't be necessary,
+ // because the registrations made by the TEST macro are executed in order
+ // within a translation unit. But this is not true of the manual registration
+ // API, and in more exotic scenarios a single file may be part of multiple
+ // translation units.
+ std::stable_sort(test_info_list_.begin(), test_info_list_.end(),
+ [](const TestInfo* const a, const TestInfo* const b) {
+ if (const int result = std::strcmp(a->file(), b->file())) {
+ return result < 0;
+ }
+
+ return a->line() < b->line();
+ });
+
// Call both legacy and the new API
repeater->OnTestSuiteStart(*this);
// Legacy API is deprecated but still available
@@ -3155,7 +3164,7 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) {
// following statements add the test part result message to the Output
// window such that the user can double-click on it to jump to the
// corresponding source code location; otherwise they do nothing.
-#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
+#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE)
// We don't call OutputDebugString*() on Windows Mobile, as printing
// to stdout is done by OutputDebugString() there already - we don't
// want the same message printed twice.
@@ -3165,8 +3174,9 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) {
}
// class PrettyUnitTestResultPrinter
-#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
- !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
+#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \
+ !defined(GTEST_OS_WINDOWS_PHONE) && !defined(GTEST_OS_WINDOWS_RT) && \
+ !defined(GTEST_OS_WINDOWS_MINGW)
// Returns the character attribute for the given color.
static WORD GetColorAttribute(GTestColor color) {
@@ -3238,22 +3248,23 @@ bool ShouldUseColor(bool stdout_is_tty) {
const char* const gtest_color = c.c_str();
if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
-#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
+#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW)
// On Windows the TERM variable is usually not set, but the
// console there does support colors.
return stdout_is_tty;
#else
// On non-Windows platforms, we rely on the TERM variable.
const char* const term = posix::GetEnv("TERM");
- const bool term_supports_color = term != nullptr && (
- String::CStringEquals(term, "xterm") ||
- String::CStringEquals(term, "xterm-color") ||
- String::CStringEquals(term, "screen") ||
- String::CStringEquals(term, "tmux") ||
- String::CStringEquals(term, "rxvt-unicode") ||
- String::CStringEquals(term, "linux") ||
- String::CStringEquals(term, "cygwin") ||
- String::EndsWithCaseInsensitive(term, "-256color"));
+ const bool term_supports_color =
+ term != nullptr && (String::CStringEquals(term, "xterm") ||
+ String::CStringEquals(term, "xterm-color") ||
+ String::CStringEquals(term, "xterm-kitty") ||
+ String::CStringEquals(term, "screen") ||
+ String::CStringEquals(term, "tmux") ||
+ String::CStringEquals(term, "rxvt-unicode") ||
+ String::CStringEquals(term, "linux") ||
+ String::CStringEquals(term, "cygwin") ||
+ String::EndsWithCaseInsensitive(term, "-256color"));
return stdout_is_tty && term_supports_color;
#endif // GTEST_OS_WINDOWS
}
@@ -3278,7 +3289,12 @@ static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
va_start(args, fmt);
static const bool in_color_mode =
+#if GTEST_HAS_FILE_SYSTEM
ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
+#else
+ false;
+#endif // GTEST_HAS_FILE_SYSTEM
+
const bool use_color = in_color_mode && (color != GTestColor::kDefault);
if (!use_color) {
@@ -3287,8 +3303,9 @@ static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
return;
}
-#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
- !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
+#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \
+ !defined(GTEST_OS_WINDOWS_PHONE) && !defined(GTEST_OS_WINDOWS_RT) && \
+ !defined(GTEST_OS_WINDOWS_MINGW)
const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
// Gets the current text color.
@@ -3883,6 +3900,7 @@ void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
// End TestEventRepeater
+#if GTEST_HAS_FILE_SYSTEM
// This class generates an XML output file.
class XmlUnitTestResultPrinter : public EmptyTestEventListener {
public:
@@ -4092,6 +4110,13 @@ std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
// Formats the given time in milliseconds as seconds.
std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
::std::stringstream ss;
+ // For the exact N seconds, makes sure output has a trailing decimal point.
+ // Sets precision so that we won't have many trailing zeros (e.g., 300 ms
+ // will be just 0.3, 410 ms 0.41, and so on)
+ ss << std::fixed
+ << std::setprecision(
+ ms % 1000 == 0 ? 0 : (ms % 100 == 0 ? 1 : (ms % 10 == 0 ? 2 : 3)))
+ << std::showpoint;
ss << (static_cast<double>(ms) * 1e-3);
return ss.str();
}
@@ -4430,7 +4455,9 @@ void XmlUnitTestResultPrinter::OutputXmlTestProperties(
}
// End XmlUnitTestResultPrinter
+#endif // GTEST_HAS_FILE_SYSTEM
+#if GTEST_HAS_FILE_SYSTEM
// This class generates an JSON output file.
class JsonUnitTestResultPrinter : public EmptyTestEventListener {
public:
@@ -4820,6 +4847,9 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
// If there was a test failure outside of one of the test suites (like in a
// test environment) include that in the output.
if (unit_test.ad_hoc_test_result().Failed()) {
+ if (comma) {
+ *stream << ",\n";
+ }
OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
}
@@ -4868,6 +4898,7 @@ std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
}
// End JsonUnitTestResultPrinter
+#endif // GTEST_HAS_FILE_SYSTEM
#if GTEST_CAN_STREAM_RESULTS_
@@ -4885,7 +4916,8 @@ std::string StreamingListener::UrlEncode(const char* str) {
case '=':
case '&':
case '\n':
- result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
+ result.push_back('%');
+ result.append(String::FormatByte(static_cast<unsigned char>(ch)));
break;
default:
result.push_back(ch);
@@ -4946,7 +4978,7 @@ const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
GTEST_LOCK_EXCLUDED_(mutex_) {
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
std::string result;
if (max_depth <= 0) {
@@ -4995,7 +5027,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
}
void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
void* caller_frame = nullptr;
if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
caller_frame = nullptr;
@@ -5006,6 +5038,7 @@ void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
#endif // GTEST_HAS_ABSL
}
+#ifdef GTEST_HAS_DEATH_TEST
// A helper class that creates the premature-exit file in its
// constructor and deletes the file in its destructor.
class ScopedPrematureExitFile {
@@ -5025,7 +5058,7 @@ class ScopedPrematureExitFile {
}
~ScopedPrematureExitFile() {
-#if !defined GTEST_OS_ESP8266
+#ifndef GTEST_OS_ESP8266
if (!premature_exit_filepath_.empty()) {
int retval = remove(premature_exit_filepath_.c_str());
if (retval) {
@@ -5043,6 +5076,7 @@ class ScopedPrematureExitFile {
ScopedPrematureExitFile(const ScopedPrematureExitFile&) = delete;
ScopedPrematureExitFile& operator=(const ScopedPrematureExitFile&) = delete;
};
+#endif // GTEST_HAS_DEATH_TEST
} // namespace internal
@@ -5292,7 +5326,7 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
msg << message;
internal::MutexLock lock(&mutex_);
- if (impl_->gtest_trace_stack().size() > 0) {
+ if (!impl_->gtest_trace_stack().empty()) {
msg << "\n" << GTEST_NAME_ << " trace:";
for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
@@ -5305,6 +5339,8 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {
msg << internal::kStackTraceMarker << os_stack_trace;
+ } else {
+ msg << "\n";
}
const TestPartResult result = TestPartResult(
@@ -5320,7 +5356,8 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
// with another testing framework) and specify the former on the
// command line for debugging.
if (GTEST_FLAG_GET(break_on_failure)) {
-#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
+#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_PHONE) && \
+ !defined(GTEST_OS_WINDOWS_RT)
// Using DebugBreak on Windows allows gtest to still break into a debugger
// when a failure happens and both the --gtest_break_on_failure and
// the --gtest_catch_exceptions flags are specified.
@@ -5330,6 +5367,10 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
(defined(__x86_64__) || defined(__i386__)))
// with clang/gcc we can achieve the same effect on x86 by invoking int3
asm("int3");
+#elif GTEST_HAS_BUILTIN(__builtin_trap)
+ __builtin_trap();
+#elif defined(SIGTRAP)
+ raise(SIGTRAP);
#else
// Dereference nullptr through a volatile pointer to prevent the compiler
// from removing. We use this rather than abort() or __builtin_trap() for
@@ -5364,6 +5405,7 @@ void UnitTest::RecordProperty(const std::string& key,
// We don't protect this under mutex_, as we only support calling it
// from the main thread.
int UnitTest::Run() {
+#ifdef GTEST_HAS_DEATH_TEST
const bool in_death_test_child_process =
GTEST_FLAG_GET(internal_run_death_test).length() > 0;
@@ -5392,31 +5434,36 @@ int UnitTest::Run() {
in_death_test_child_process
? nullptr
: internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
+#else
+ const bool in_death_test_child_process = false;
+#endif // GTEST_HAS_DEATH_TEST
// Captures the value of GTEST_FLAG(catch_exceptions). This value will be
// used for the duration of the program.
impl()->set_catch_exceptions(GTEST_FLAG_GET(catch_exceptions));
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Either the user wants Google Test to catch exceptions thrown by the
// tests or this is executing in the context of death test child
// process. In either case the user does not want to see pop-up dialogs
// about crashes - they are expected.
if (impl()->catch_exceptions() || in_death_test_child_process) {
-#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
+#if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_WINDOWS_PHONE) && \
+ !defined(GTEST_OS_WINDOWS_RT)
// SetErrorMode doesn't exist on CE.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
#endif // !GTEST_OS_WINDOWS_MOBILE
-#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
+#if (defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW)) && \
+ !defined(GTEST_OS_WINDOWS_MOBILE)
// Death test children can be terminated with _abort(). On Windows,
// _abort() can show a dialog with a warning message. This forces the
// abort message to go to stderr instead.
_set_error_mode(_OUT_TO_STDERR);
#endif
-#if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
+#if defined(_MSC_VER) && !defined(GTEST_OS_WINDOWS_MOBILE)
// In the debug version, Visual Studio pops up a separate dialog
// offering a choice to debug the aborted program. We need to suppress
// this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
@@ -5438,6 +5485,8 @@ int UnitTest::Run() {
}
#endif
}
+#else
+ (void)in_death_test_child_process; // Needed inside the #if block above
#endif // GTEST_OS_WINDOWS
return internal::HandleExceptionsInMethodIfSupported(
@@ -5447,11 +5496,13 @@ int UnitTest::Run() {
: 1;
}
+#if GTEST_HAS_FILE_SYSTEM
// Returns the working directory when the first TEST() or TEST_F() was
// executed.
const char* UnitTest::original_working_dir() const {
return impl_->original_working_dir_.c_str();
}
+#endif // GTEST_HAS_FILE_SYSTEM
// Returns the TestSuite object for the test that's currently running,
// or NULL if no test is running.
@@ -5531,7 +5582,7 @@ UnitTestImpl::UnitTestImpl(UnitTest* parent)
random_(0), // Will be reseeded before first use.
start_timestamp_(0),
elapsed_time_(0),
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
death_test_factory_(new DefaultDeathTestFactory),
#endif
// Will be overridden by the flag before first use.
@@ -5571,11 +5622,11 @@ void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
test_result->RecordProperty(xml_element, test_property);
}
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
// Disables event forwarding if the control is currently in a death test
// subprocess. Must not be called before InitGoogleTest.
void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
- if (internal_run_death_test_flag_.get() != nullptr)
+ if (internal_run_death_test_flag_ != nullptr)
listeners()->SuppressEventForwarding();
}
#endif // GTEST_HAS_DEATH_TEST
@@ -5584,16 +5635,21 @@ void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
// UnitTestOptions. Must not be called before InitGoogleTest.
void UnitTestImpl::ConfigureXmlOutput() {
const std::string& output_format = UnitTestOptions::GetOutputFormat();
+#if GTEST_HAS_FILE_SYSTEM
if (output_format == "xml") {
listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
} else if (output_format == "json") {
listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
- } else if (output_format != "") {
+ } else if (!output_format.empty()) {
GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \""
<< output_format << "\" ignored.";
}
+#else
+ GTEST_LOG_(ERROR) << "ERROR: alternative output formats require "
+ << "GTEST_HAS_FILE_SYSTEM to be enabled";
+#endif // GTEST_HAS_FILE_SYSTEM
}
#if GTEST_CAN_STREAM_RESULTS_
@@ -5629,7 +5685,7 @@ void UnitTestImpl::PostFlagParsingInit() {
listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
#endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
InitDeathTestSubprocessControlInfo();
SuppressTestEventsIfInSubprocess();
#endif // GTEST_HAS_DEATH_TEST
@@ -5652,7 +5708,7 @@ void UnitTestImpl::PostFlagParsingInit() {
ConfigureStreamingOutput();
#endif // GTEST_CAN_STREAM_RESULTS_
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
if (GTEST_FLAG_GET(install_failure_signal_handler)) {
absl::FailureSignalHandlerOptions options;
absl::InstallFailureSignalHandler(options);
@@ -5756,18 +5812,19 @@ bool UnitTestImpl::RunAllTests() {
// user didn't call InitGoogleTest.
PostFlagParsingInit();
+#if GTEST_HAS_FILE_SYSTEM
// Even if sharding is not on, test runners may want to use the
// GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
// protocol.
internal::WriteToShardStatusFileIfNeeded();
+#endif // GTEST_HAS_FILE_SYSTEM
// True if and only if we are in a subprocess for running a thread-safe-style
// death test.
bool in_subprocess_for_death_test = false;
-#if GTEST_HAS_DEATH_TEST
- in_subprocess_for_death_test =
- (internal_run_death_test_flag_.get() != nullptr);
+#ifdef GTEST_HAS_DEATH_TEST
+ in_subprocess_for_death_test = (internal_run_death_test_flag_ != nullptr);
#if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
if (in_subprocess_for_death_test) {
GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
@@ -5930,15 +5987,12 @@ bool UnitTestImpl::RunAllTests() {
"() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
" will start to enforce the valid usage. "
"Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
-#if GTEST_FOR_GOOGLE_
- ColoredPrintf(GTestColor::kRed,
- "For more details, see http://wiki/Main/ValidGUnitMain.\n");
-#endif // GTEST_FOR_GOOGLE_
}
return !failed;
}
+#if GTEST_HAS_FILE_SYSTEM
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
// if the variable is present. If a file already exists at this location, this
// function will write over it. If the variable is present, but the file cannot
@@ -5958,6 +6012,7 @@ void WriteToShardStatusFileIfNeeded() {
fclose(file);
}
}
+#endif // GTEST_HAS_FILE_SYSTEM
// Checks whether sharding is enabled by examining the relevant
// environment variable values. If the variables are present,
@@ -6149,6 +6204,7 @@ void UnitTestImpl::ListTestsMatchingFilter() {
}
}
fflush(stdout);
+#if GTEST_HAS_FILE_SYSTEM
const std::string& output_format = UnitTestOptions::GetOutputFormat();
if (output_format == "xml" || output_format == "json") {
FILE* fileout = OpenFileForWriting(
@@ -6166,6 +6222,7 @@ void UnitTestImpl::ListTestsMatchingFilter() {
fprintf(fileout, "%s", StringStreamToString(&stream).c_str());
fclose(fileout);
}
+#endif // GTEST_HAS_FILE_SYSTEM
}
// Sets the OS stack trace getter.
@@ -6485,7 +6542,7 @@ static const char kColorEncodedHelpMessage[] =
#endif // GTEST_CAN_STREAM_RESULTS_
"\n"
"Assertion Behavior:\n"
-#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
+#if defined(GTEST_HAS_DEATH_TEST) && !defined(GTEST_OS_WINDOWS)
" @G--" GTEST_FLAG_PREFIX_
"death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
" Set the default death test style.\n"
@@ -6554,7 +6611,7 @@ static bool ParseGoogleTestFlag(const char* const arg) {
return false;
}
-#if GTEST_USE_OWN_FLAGFILE_FLAG_
+#if GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
static void LoadFlagsFromFile(const std::string& path) {
FILE* flagfile = posix::FOpen(path.c_str(), "r");
if (!flagfile) {
@@ -6570,7 +6627,7 @@ static void LoadFlagsFromFile(const std::string& path) {
if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true;
}
}
-#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
+#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
// Parses the command line for Google Test flags, without initializing
// other parts of Google Test. The type parameter CharType can be
@@ -6587,12 +6644,12 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
bool remove_flag = false;
if (ParseGoogleTestFlag(arg)) {
remove_flag = true;
-#if GTEST_USE_OWN_FLAGFILE_FLAG_
+#if GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
} else if (ParseFlag(arg, "flagfile", &flagfile_value)) {
GTEST_FLAG_SET(flagfile, flagfile_value);
LoadFlagsFromFile(flagfile_value);
remove_flag = true;
-#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
+#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM
} else if (arg_string == "--help" || HasGoogleTestFlagPrefix(arg)) {
// Both help flag and unrecognized Google Test flags (excluding
// internal ones) trigger help display.
@@ -6628,12 +6685,11 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
// Parses the command line for Google Test flags, without initializing
// other parts of Google Test.
void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
if (*argc > 0) {
// absl::ParseCommandLine() requires *argc > 0.
auto positional_args = absl::flags_internal::ParseCommandLineImpl(
- *argc, argv, absl::flags_internal::ArgvListAction::kRemoveParsedArgs,
- absl::flags_internal::UsageFlagsAction::kHandleUsage,
+ *argc, argv, absl::flags_internal::UsageFlagsAction::kHandleUsage,
absl::flags_internal::OnUndefinedFlag::kReportUndefined);
// Any command-line positional arguments not part of any command-line flag
// (or arguments to a flag) are copied back out to argv, with the program
@@ -6653,7 +6709,7 @@ void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
// Fix the value of *_NSGetArgc() on macOS, but if and only if
// *_NSGetArgv() == argv
// Only applicable to char** version of argv
-#if GTEST_OS_MAC
+#ifdef GTEST_OS_MAC
#ifndef GTEST_OS_IOS
if (*_NSGetArgv() == argv) {
*_NSGetArgc() = *argc;
@@ -6681,7 +6737,7 @@ void InitGoogleTestImpl(int* argc, CharType** argv) {
g_argvs.push_back(StreamableToString(argv[i]));
}
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
absl::InitializeSymbolizer(g_argvs[0].c_str());
// When using the Abseil Flags library, set the program usage message to the
@@ -6740,12 +6796,13 @@ void InitGoogleTest() {
#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
}
-#if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
-// Return value of first environment variable that is set and contains
-// a non-empty string. If there are none, return the "fallback" string.
-// Since we like the temporary directory to have a directory separator suffix,
-// add it if not provided in the environment variable value.
-static std::string GetTempDirFromEnv(
+#if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) || \
+ !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
+// Returns the value of the first environment variable that is set and contains
+// a non-empty string. If there are none, returns the "fallback" string. Adds
+// the director-separator character as a suffix if not provided in the
+// environment variable value.
+static std::string GetDirFromEnv(
std::initializer_list<const char*> environment_variables,
const char* fallback, char separator) {
for (const char* variable_name : environment_variables) {
@@ -6764,15 +6821,41 @@ static std::string GetTempDirFromEnv(
std::string TempDir() {
#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
-#elif GTEST_OS_WINDOWS || GTEST_OS_WINDOWS_MOBILE
- return GetTempDirFromEnv({"TEST_TMPDIR", "TEMP"}, "\\temp\\", '\\');
-#elif GTEST_OS_LINUX_ANDROID
- return GetTempDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/data/local/tmp/", '/');
+#elif defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE)
+ return GetDirFromEnv({"TEST_TMPDIR", "TEMP"}, "\\temp\\", '\\');
+#elif defined(GTEST_OS_LINUX_ANDROID)
+ return GetDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/data/local/tmp/", '/');
#else
- return GetTempDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/tmp/", '/');
+ return GetDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/tmp/", '/');
#endif
}
+#if GTEST_HAS_FILE_SYSTEM && !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
+// Returns the directory path (including terminating separator) of the current
+// executable as derived from argv[0].
+static std::string GetCurrentExecutableDirectory() {
+ internal::FilePath argv_0(internal::GetArgvs()[0]);
+ return argv_0.RemoveFileName().string();
+}
+#endif
+
+#if GTEST_HAS_FILE_SYSTEM
+std::string SrcDir() {
+#if defined(GTEST_CUSTOM_SRCDIR_FUNCTION_)
+ return GTEST_CUSTOM_SRCDIR_FUNCTION_();
+#elif defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE)
+ return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
+ '\\');
+#elif defined(GTEST_OS_LINUX_ANDROID)
+ return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
+ '/');
+#else
+ return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(),
+ '/');
+#endif
+}
+#endif
+
// Class ScopedTrace
// Pushes the given source file location and message onto a per-thread
diff --git a/googletest/src/gtest_main.cc b/googletest/src/gtest_main.cc
index 4497637..c2e3b3c 100644
--- a/googletest/src/gtest_main.cc
+++ b/googletest/src/gtest_main.cc
@@ -31,19 +31,31 @@
#include "gtest/gtest.h"
-#if GTEST_OS_ESP8266 || GTEST_OS_ESP32
-#if GTEST_OS_ESP8266
+#if defined(GTEST_OS_ESP8266) || defined(GTEST_OS_ESP32)
+// Arduino-like platforms: program entry points are setup/loop instead of main.
+
+#ifdef GTEST_OS_ESP8266
extern "C" {
#endif
+
void setup() { testing::InitGoogleTest(); }
void loop() { RUN_ALL_TESTS(); }
-#if GTEST_OS_ESP8266
+#ifdef GTEST_OS_ESP8266
}
#endif
+#elif defined(GTEST_OS_QURT)
+// QuRT: program entry point is main, but argc/argv are unusable.
+
+GTEST_API_ int main() {
+ printf("Running main() from %s\n", __FILE__);
+ testing::InitGoogleTest();
+ return RUN_ALL_TESTS();
+}
#else
+// Normal platforms: program entry point is main, argc/argv are initialized.
GTEST_API_ int main(int argc, char **argv) {
printf("Running main() from %s\n", __FILE__);
diff --git a/googletest/test/googletest-break-on-failure-unittest.py b/googletest/test/googletest-break-on-failure-unittest.py
index 4eafba3..e314b5c 100755
--- a/googletest/test/googletest-break-on-failure-unittest.py
+++ b/googletest/test/googletest-break-on-failure-unittest.py
@@ -59,7 +59,8 @@ 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_')
+ 'googletest-break-on-failure-unittest_'
+)
environ = gtest_test_utils.environ
@@ -87,22 +88,26 @@ def Run(command):
class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase):
- """Tests using the GTEST_BREAK_ON_FAILURE environment variable or
+ """Unit test for Google Test's break-on-failure mode.
+
+ 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
+ """Runs googletest-break-on-failure-unittest_ and verifies its behavior.
+
+ 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.
+ 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)
@@ -132,74 +137,56 @@ class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase):
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)
+ 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.assertTrue(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)
+ 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)
+ 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)
+ 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)
+ 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)
+ 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)
+ self.RunAndVerify(env_var_value='1', flag_value='1', expect_seg_fault=1)
finally:
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, None)
diff --git a/googletest/test/googletest-break-on-failure-unittest_.cc b/googletest/test/googletest-break-on-failure-unittest_.cc
index 324294f..337e34c 100644
--- a/googletest/test/googletest-break-on-failure-unittest_.cc
+++ b/googletest/test/googletest-break-on-failure-unittest_.cc
@@ -39,7 +39,7 @@
#include "gtest/gtest.h"
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
#include <stdlib.h>
#include <windows.h>
#endif
@@ -49,7 +49,7 @@ namespace {
// A test that's expected to fail.
TEST(Foo, Bar) { EXPECT_EQ(2, 3); }
-#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
+#if GTEST_HAS_SEH && !defined(GTEST_OS_WINDOWS_MOBILE)
// On Windows Mobile global exception handlers are not supported.
LONG WINAPI
ExitWithExceptionCode(struct _EXCEPTION_POINTERS* exception_pointers) {
@@ -60,12 +60,12 @@ ExitWithExceptionCode(struct _EXCEPTION_POINTERS* exception_pointers) {
} // namespace
int main(int argc, char** argv) {
-#if GTEST_OS_WINDOWS
+#ifdef 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
+#if GTEST_HAS_SEH && !defined(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
diff --git a/googletest/test/googletest-catch-exceptions-test.py b/googletest/test/googletest-catch-exceptions-test.py
index d38d91a..ee4dc9a 100755
--- a/googletest/test/googletest-catch-exceptions-test.py
+++ b/googletest/test/googletest-catch-exceptions-test.py
@@ -46,12 +46,14 @@ FILTER_FLAG = FLAG_PREFIX + 'filter'
# 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_')
+ 'googletest-catch-exceptions-ex-test_'
+)
# 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
@@ -64,7 +66,8 @@ SetEnvVar = gtest_test_utils.SetEnvVar
SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)
TEST_LIST = gtest_test_utils.Subprocess(
- [EXE_PATH, LIST_TESTS_FLAG], env=environ).output
+ [EXE_PATH, LIST_TESTS_FLAG], env=environ
+).output
SUPPORTS_SEH_EXCEPTIONS = 'ThrowsSehException' in TEST_LIST
@@ -72,33 +75,47 @@ 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
+ [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 SetUpTestSuite()'
- in test_output)
- self.assert_('SEH exception with code 0x2a thrown in TearDownTestSuite()'
- 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)
+ self.assertIn(
+ (
+ 'SEH exception with code 0x2a thrown '
+ "in the test fixture's constructor"
+ ),
+ test_output,
+ )
+ self.assertIn(
+ (
+ 'SEH exception with code 0x2a thrown '
+ "in the test fixture's destructor"
+ ),
+ test_output,
+ )
+ self.assertIn(
+ 'SEH exception with code 0x2a thrown in SetUpTestSuite()', test_output
+ )
+ self.assertIn(
+ 'SEH exception with code 0x2a thrown in TearDownTestSuite()',
+ test_output,
+ )
+ self.assertIn(
+ 'SEH exception with code 0x2a thrown in SetUp()', test_output
+ )
+ self.assertIn(
+ 'SEH exception with code 0x2a thrown in TearDown()', test_output
+ )
+ self.assertIn(
+ 'SEH exception with code 0x2a thrown in the test body', test_output
+ )
def testCatchesSehExceptionsWithCxxExceptionsEnabled(self):
self.TestSehExceptions(EX_BINARY_OUTPUT)
@@ -110,111 +127,172 @@ if SUPPORTS_SEH_EXCEPTIONS:
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.
+ 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.assertTrue(
'C++ exception with description '
'"Standard C++ exception" thrown '
- 'in the test fixture\'s constructor' in EX_BINARY_OUTPUT,
- 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):
+ "in the test fixture's constructor"
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
+ self.assertTrue(
+ '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.assertTrue(
'C++ exception with description '
'"Standard C++ exception" thrown '
- 'in the test fixture\'s destructor' in EX_BINARY_OUTPUT,
- EX_BINARY_OUTPUT)
+ "in the test fixture's destructor"
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
'CxxExceptionInDestructorTest::TearDownTestSuite() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
def testCatchesCxxExceptionsInSetUpTestCase(self):
self.assertTrue(
'C++ exception with description "Standard C++ exception"'
- ' thrown in SetUpTestSuite()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ ' thrown in SetUpTestSuite()'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInConstructorTest::TearDownTestSuite() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInConstructorTest::TearDownTestSuite() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertFalse(
- 'CxxExceptionInSetUpTestSuiteTest constructor '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInSetUpTestSuiteTest constructor called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertFalse(
- 'CxxExceptionInSetUpTestSuiteTest destructor '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInSetUpTestSuiteTest destructor called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertFalse(
- 'CxxExceptionInSetUpTestSuiteTest::SetUp() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInSetUpTestSuiteTest::SetUp() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertFalse(
- 'CxxExceptionInSetUpTestSuiteTest::TearDown() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInSetUpTestSuiteTest::TearDown() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertFalse(
- 'CxxExceptionInSetUpTestSuiteTest test body '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInSetUpTestSuiteTest test body called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
def testCatchesCxxExceptionsInTearDownTestCase(self):
self.assertTrue(
'C++ exception with description "Standard C++ exception"'
- ' thrown in TearDownTestSuite()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ ' thrown in TearDownTestSuite()'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
def testCatchesCxxExceptionsInSetUp(self):
self.assertTrue(
'C++ exception with description "Standard C++ exception"'
- ' thrown in SetUp()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ ' thrown in SetUp()'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
+ self.assertTrue(
+ 'CxxExceptionInSetUpTest::TearDownTestSuite() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInSetUpTest::TearDownTestSuite() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInSetUpTest destructor called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInSetUpTest destructor '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInSetUpTest::TearDown() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInSetUpTest::TearDown() '
- 'called as expected.' in EX_BINARY_OUTPUT, 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"')
+ '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.assertTrue(
'C++ exception with description "Standard C++ exception"'
- ' thrown in TearDown()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ ' thrown in TearDown()'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInTearDownTest::TearDownTestSuite() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInTearDownTest::TearDownTestSuite() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInTearDownTest destructor '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInTearDownTest destructor called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
def testCatchesCxxExceptionsInTestBody(self):
self.assertTrue(
'C++ exception with description "Standard C++ exception"'
- ' thrown in the test body' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ ' thrown in the test body'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInTestBodyTest::TearDownTestSuite() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInTestBodyTest::TearDownTestSuite() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInTestBodyTest destructor '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInTestBodyTest destructor called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
self.assertTrue(
- 'CxxExceptionInTestBodyTest::TearDown() '
- 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
+ 'CxxExceptionInTestBodyTest::TearDown() called as expected.'
+ in EX_BINARY_OUTPUT,
+ EX_BINARY_OUTPUT,
+ )
def testCatchesNonStdCxxExceptions(self):
self.assertTrue(
'Unknown C++ exception thrown in the test body' in EX_BINARY_OUTPUT,
- EX_BINARY_OUTPUT)
+ EX_BINARY_OUTPUT,
+ )
def testUnhandledCxxExceptionsAbortTheProgram(self):
# Filters out SEH exception tests on Windows. Unhandled SEH exceptions
@@ -222,14 +300,15 @@ class CatchCxxExceptionsTest(gtest_test_utils.TestCase):
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)
+ [EX_EXE_PATH, NO_CATCH_EXCEPTIONS_FLAG, FITLER_OUT_SEH_TESTS_FLAG],
+ env=environ,
+ ).output
+
+ self.assertIn(
+ 'Unhandled C++ exception terminating the program',
+ uncaught_exceptions_ex_binary_output,
+ )
+ self.assertNotIn('unexpected', uncaught_exceptions_ex_binary_output)
if __name__ == '__main__':
diff --git a/googletest/test/googletest-color-test.py b/googletest/test/googletest-color-test.py
index c22752d..8926a48 100755
--- a/googletest/test/googletest-color-test.py
+++ b/googletest/test/googletest-color-test.py
@@ -65,62 +65,64 @@ def UsesColor(term, color_env_var, color_flag):
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))
+ self.assertTrue(not UsesColor('dumb', None, None))
+ self.assertTrue(not UsesColor('emacs', None, None))
+ self.assertTrue(not UsesColor('xterm-mono', None, None))
+ self.assertTrue(not UsesColor('unknown', None, None))
+ self.assertTrue(not UsesColor(None, None, None))
+ self.assertTrue(UsesColor('linux', None, None))
+ self.assertTrue(UsesColor('cygwin', None, None))
+ self.assertTrue(UsesColor('xterm', None, None))
+ self.assertTrue(UsesColor('xterm-color', None, None))
+ self.assertTrue(UsesColor('xterm-kitty', None, None))
+ self.assertTrue(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'))
+ self.assertTrue(not UsesColor('dumb', None, 'no'))
+ self.assertTrue(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'))
+ self.assertTrue(not UsesColor('emacs', None, 'auto'))
+ self.assertTrue(UsesColor('xterm', None, 'auto'))
+ self.assertTrue(UsesColor('dumb', None, 'yes'))
+ self.assertTrue(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))
+ self.assertTrue(not UsesColor('dumb', 'no', None))
+ self.assertTrue(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))
+ self.assertTrue(not UsesColor('dumb', 'auto', None))
+ self.assertTrue(UsesColor('xterm-color', 'auto', None))
+ self.assertTrue(UsesColor('dumb', 'yes', None))
+ self.assertTrue(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'))
+ self.assertTrue(not UsesColor('xterm-color', 'no', 'no'))
+ self.assertTrue(UsesColor('dumb', 'no', 'yes'))
+ self.assertTrue(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.assertTrue(UsesColor('dumb', None, 'true'))
+ self.assertTrue(UsesColor('dumb', None, 'YES'))
+ self.assertTrue(UsesColor('dumb', None, 'T'))
+ self.assertTrue(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'))
+ self.assertTrue(not UsesColor('xterm', None, 'f'))
+ self.assertTrue(not UsesColor('xterm', None, 'false'))
+ self.assertTrue(not UsesColor('xterm', None, '0'))
+ self.assertTrue(not UsesColor('xterm', None, 'unknown'))
if __name__ == '__main__':
diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc
index 4737ff9..3579ce8 100644
--- a/googletest/test/googletest-death-test-test.cc
+++ b/googletest/test/googletest-death-test-test.cc
@@ -37,9 +37,9 @@
using testing::internal::AlwaysFalse;
using testing::internal::AlwaysTrue;
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
#include <direct.h> // For chdir().
#include <fcntl.h> // For O_BINARY
#include <io.h>
@@ -52,7 +52,7 @@ using testing::internal::AlwaysTrue;
#include <signal.h>
#include <stdio.h>
-#if GTEST_OS_LINUX
+#ifdef GTEST_OS_LINUX
#include <sys/time.h>
#endif // GTEST_OS_LINUX
@@ -200,7 +200,7 @@ int DieInDebugElse12(int* sideeffect) {
return 12;
}
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Death in dbg due to Windows CRT assertion failure, not opt.
int DieInCRTDebugElse12(int* sideeffect) {
@@ -220,7 +220,7 @@ int DieInCRTDebugElse12(int* sideeffect) {
#endif // GTEST_OS_WINDOWS
-#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)
// Tests the ExitedWithCode predicate.
TEST(ExitStatusPredicateTest, ExitedWithCode) {
@@ -327,23 +327,6 @@ TEST_F(TestForDeathTest, SingleStatement) {
#pragma GCC diagnostic pop
#endif
-#if GTEST_USES_PCRE
-
-void DieWithEmbeddedNul() {
- fprintf(stderr, "Hello%cmy null world.\n", '\0');
- fflush(stderr);
- _exit(1);
-}
-
-// 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) {
@@ -391,7 +374,7 @@ TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
ASSERT_DEATH(_exit(1), "");
}
-#if GTEST_OS_LINUX
+#ifdef GTEST_OS_LINUX
void SigprofAction(int, siginfo_t*, void*) { /* no op */
}
@@ -521,16 +504,12 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
const testing::internal::RE regex(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex);
-#if !GTEST_USES_PCRE
-
const ::std::string regex_std_str(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex_std_str);
// This one is tricky; a temporary pointer into another temporary. Reference
// lifetime extension of the pointer is not sufficient.
EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str());
-
-#endif // !GTEST_USES_PCRE
}
// Tests that a non-void function can be used in a death test.
@@ -662,7 +641,7 @@ TEST_F(TestForDeathTest, TestExpectDebugDeath) {
#endif
}
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/crtsetreportmode
// In debug mode, the calls to _CrtSetReportMode and _CrtSetReportFile enable
@@ -714,7 +693,7 @@ void ExpectDebugDeathHelper(bool* aborted) {
*aborted = false;
}
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
printf(
"This test should be considered failing if it shows "
@@ -826,14 +805,14 @@ static void TestExitMacros() {
EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Of all signals effects on the process exit code, only those of SIGABRT
// are documented on Windows.
// See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c.
EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
-#elif !GTEST_OS_FUCHSIA
+#elif !defined(GTEST_OS_FUCHSIA)
// Fuchsia has no unix signals.
EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
@@ -1198,7 +1177,7 @@ TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
EXPECT_STREQ("", GetLastErrnoDescription().c_str());
}
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
TEST(AutoHandleTest, AutoHandleWorks) {
HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
ASSERT_NE(INVALID_HANDLE_VALUE, handle);
@@ -1225,7 +1204,7 @@ TEST(AutoHandleTest, AutoHandleWorks) {
}
#endif // GTEST_OS_WINDOWS
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
typedef unsigned __int64 BiggestParsable;
typedef signed __int64 BiggestSignedParsable;
#else
@@ -1322,7 +1301,7 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
EXPECT_EQ(123, char_result);
}
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
TEST(EnvironmentTest, HandleFitsIntoSizeT) {
ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
}
@@ -1374,7 +1353,7 @@ void DieWithMessage(const char* message) {
TEST(MatcherDeathTest, DoesNotBreakBareRegexMatching) {
// googletest tests this, of course; here we ensure that including googlemock
// has not broken it.
-#if GTEST_USES_POSIX_RE
+#ifdef GTEST_USES_POSIX_RE
EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I d[aeiou]e");
#else
EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I di?e");
diff --git a/googletest/test/googletest-death-test_ex_test.cc b/googletest/test/googletest-death-test_ex_test.cc
index f2515e3..34d5501 100644
--- a/googletest/test/googletest-death-test_ex_test.cc
+++ b/googletest/test/googletest-death-test_ex_test.cc
@@ -33,7 +33,7 @@
#include "gtest/gtest-death-test.h"
#include "gtest/gtest.h"
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_SEH
#include <windows.h> // For RaiseException().
diff --git a/googletest/test/googletest-env-var-test.py b/googletest/test/googletest-env-var-test.py
index bc4d87d..24d8edb 100755
--- a/googletest/test/googletest-env-var-test.py
+++ b/googletest/test/googletest-env-var-test.py
@@ -101,7 +101,6 @@ class GTestEnvVarTest(gtest_test_utils.TestCase):
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."""
@@ -116,5 +115,6 @@ class GTestEnvVarTest(gtest_test_utils.TestCase):
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-failfast-unittest.py b/googletest/test/googletest-failfast-unittest.py
index 1356d4f..cdbce0c 100755
--- a/googletest/test/googletest-failfast-unittest.py
+++ b/googletest/test/googletest-failfast-unittest.py
@@ -62,15 +62,18 @@ FILTER_FLAG = 'gtest_filter'
# Command to run the googletest-failfast-unittest_ program.
COMMAND = gtest_test_utils.GetTestExecutablePath(
- 'googletest-failfast-unittest_')
+ 'googletest-failfast-unittest_'
+)
# 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
+SUPPORTS_DEATH_TESTS = (
+ 'HasDeathTest'
+ in gtest_test_utils.Subprocess([COMMAND, LIST_TESTS_FLAG]).output
+)
# Utilities.
@@ -90,8 +93,9 @@ def RunAndReturnOutput(test_suite=None, fail_fast=None, run_disabled=False):
"""Runs the test program and returns its output."""
args = []
- xml_path = os.path.join(gtest_test_utils.GetTempDir(),
- '.GTestFailFastUnitTest.xml')
+ xml_path = os.path.join(
+ gtest_test_utils.GetTempDir(), '.GTestFailFastUnitTest.xml'
+ )
args += ['--gtest_output=xml:' + xml_path]
if fail_fast is not None:
if isinstance(fail_fast, str):
@@ -188,49 +192,63 @@ class GTestFailFastUnitTest(gtest_test_utils.TestCase):
txt, _ = RunAndReturnOutput(test_suite='HasSkipTest', fail_fast=True)
self.assertIn('1 FAILED TEST', txt)
self.assertIn('[ SKIPPED ] 3 tests', txt)
- for expected_count, callback in [(1, 'OnTestSuiteStart'),
- (5, 'OnTestStart'),
- (5, 'OnTestEnd'),
- (5, 'OnTestPartResult'),
- (1, 'OnTestSuiteEnd')]:
+ for expected_count, callback in [
+ (1, 'OnTestSuiteStart'),
+ (5, 'OnTestStart'),
+ (5, 'OnTestEnd'),
+ (5, 'OnTestPartResult'),
+ (1, 'OnTestSuiteEnd'),
+ ]:
self.assertEqual(
- expected_count, txt.count(callback),
- 'Expected %d calls to callback %s match count on output: %s ' %
- (expected_count, callback, txt))
+ expected_count,
+ txt.count(callback),
+ 'Expected %d calls to callback %s match count on output: %s '
+ % (expected_count, callback, txt),
+ )
txt, _ = RunAndReturnOutput(test_suite='HasSkipTest', fail_fast=False)
self.assertIn('3 FAILED TEST', txt)
self.assertIn('[ SKIPPED ] 1 test', txt)
- for expected_count, callback in [(1, 'OnTestSuiteStart'),
- (5, 'OnTestStart'),
- (5, 'OnTestEnd'),
- (5, 'OnTestPartResult'),
- (1, 'OnTestSuiteEnd')]:
+ for expected_count, callback in [
+ (1, 'OnTestSuiteStart'),
+ (5, 'OnTestStart'),
+ (5, 'OnTestEnd'),
+ (5, 'OnTestPartResult'),
+ (1, 'OnTestSuiteEnd'),
+ ]:
self.assertEqual(
- expected_count, txt.count(callback),
- 'Expected %d calls to callback %s match count on output: %s ' %
- (expected_count, callback, txt))
+ expected_count,
+ txt.count(callback),
+ 'Expected %d calls to callback %s match count on output: %s '
+ % (expected_count, callback, txt),
+ )
def assertXmlResultCount(self, result, count, xml):
self.assertEqual(
- count, xml.count('result="%s"' % result),
- 'Expected \'result="%s"\' match count of %s: %s ' %
- (result, count, xml))
+ count,
+ xml.count('result="%s"' % result),
+ 'Expected \'result="%s"\' match count of %s: %s '
+ % (result, count, xml),
+ )
def assertXmlStatusCount(self, status, count, xml):
self.assertEqual(
- count, xml.count('status="%s"' % status),
- 'Expected \'status="%s"\' match count of %s: %s ' %
- (status, count, xml))
-
- def assertFailFastXmlAndTxtOutput(self,
- fail_fast,
- test_suite,
- passed_count,
- failure_count,
- skipped_count,
- suppressed_count,
- run_disabled=False):
+ count,
+ xml.count('status="%s"' % status),
+ 'Expected \'status="%s"\' match count of %s: %s '
+ % (status, count, xml),
+ )
+
+ def assertFailFastXmlAndTxtOutput(
+ self,
+ fail_fast,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled=False,
+ ):
"""Assert XML and text output of a test execution."""
txt, xml = RunAndReturnOutput(test_suite, fail_fast, run_disabled)
@@ -240,40 +258,57 @@ class GTestFailFastUnitTest(gtest_test_utils.TestCase):
self.assertIn('%s DISABLED TEST' % suppressed_count, txt)
if skipped_count > 0:
self.assertIn('[ SKIPPED ] %s tests' % skipped_count, txt)
- self.assertXmlStatusCount('run',
- passed_count + failure_count + skipped_count, xml)
+ self.assertXmlStatusCount(
+ 'run', passed_count + failure_count + skipped_count, xml
+ )
self.assertXmlStatusCount('notrun', suppressed_count, xml)
self.assertXmlResultCount('completed', passed_count + failure_count, xml)
self.assertXmlResultCount('skipped', skipped_count, xml)
self.assertXmlResultCount('suppressed', suppressed_count, xml)
- def assertFailFastBehavior(self,
- test_suite,
- passed_count,
- failure_count,
- skipped_count,
- suppressed_count,
- run_disabled=False):
+ def assertFailFastBehavior(
+ self,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled=False,
+ ):
"""Assert --fail_fast via flag."""
for fail_fast in ('true', '1', 't', True):
- self.assertFailFastXmlAndTxtOutput(fail_fast, test_suite, passed_count,
- failure_count, skipped_count,
- suppressed_count, run_disabled)
-
- def assertNotFailFastBehavior(self,
- test_suite,
- passed_count,
- failure_count,
- skipped_count,
- suppressed_count,
- run_disabled=False):
+ self.assertFailFastXmlAndTxtOutput(
+ fail_fast,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled,
+ )
+
+ def assertNotFailFastBehavior(
+ self,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled=False,
+ ):
"""Assert --nofail_fast via flag."""
for fail_fast in ('false', '0', 'f', False):
- self.assertFailFastXmlAndTxtOutput(fail_fast, test_suite, passed_count,
- failure_count, skipped_count,
- suppressed_count, run_disabled)
+ self.assertFailFastXmlAndTxtOutput(
+ fail_fast,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled,
+ )
def testFlag_HasFixtureTest(self):
"""Tests the behavior of fail_fast and TEST_F."""
@@ -282,13 +317,15 @@ class GTestFailFastUnitTest(gtest_test_utils.TestCase):
passed_count=1,
failure_count=1,
skipped_count=3,
- suppressed_count=0)
+ suppressed_count=0,
+ )
self.assertNotFailFastBehavior(
test_suite='HasFixtureTest',
passed_count=1,
failure_count=4,
skipped_count=0,
- suppressed_count=0)
+ suppressed_count=0,
+ )
def testFlag_HasSimpleTest(self):
"""Tests the behavior of fail_fast and TEST."""
@@ -297,13 +334,15 @@ class GTestFailFastUnitTest(gtest_test_utils.TestCase):
passed_count=1,
failure_count=1,
skipped_count=3,
- suppressed_count=0)
+ suppressed_count=0,
+ )
self.assertNotFailFastBehavior(
test_suite='HasSimpleTest',
passed_count=1,
failure_count=4,
skipped_count=0,
- suppressed_count=0)
+ suppressed_count=0,
+ )
def testFlag_HasParametersTest(self):
"""Tests the behavior of fail_fast and TEST_P."""
@@ -312,13 +351,15 @@ class GTestFailFastUnitTest(gtest_test_utils.TestCase):
passed_count=0,
failure_count=1,
skipped_count=3,
- suppressed_count=0)
+ suppressed_count=0,
+ )
self.assertNotFailFastBehavior(
test_suite='HasParametersSuite/HasParametersTest',
passed_count=0,
failure_count=4,
skipped_count=0,
- suppressed_count=0)
+ suppressed_count=0,
+ )
def testFlag_HasDisabledTest(self):
"""Tests the behavior of fail_fast and Disabled test cases."""
@@ -328,14 +369,16 @@ class GTestFailFastUnitTest(gtest_test_utils.TestCase):
failure_count=1,
skipped_count=2,
suppressed_count=1,
- run_disabled=False)
+ run_disabled=False,
+ )
self.assertNotFailFastBehavior(
test_suite='HasDisabledTest',
passed_count=1,
failure_count=3,
skipped_count=0,
suppressed_count=1,
- run_disabled=False)
+ run_disabled=False,
+ )
def testFlag_HasDisabledRunDisabledTest(self):
"""Tests the behavior of fail_fast and Disabled test cases enabled."""
@@ -345,14 +388,16 @@ class GTestFailFastUnitTest(gtest_test_utils.TestCase):
failure_count=1,
skipped_count=3,
suppressed_count=0,
- run_disabled=True)
+ run_disabled=True,
+ )
self.assertNotFailFastBehavior(
test_suite='HasDisabledTest',
passed_count=1,
failure_count=4,
skipped_count=0,
suppressed_count=0,
- run_disabled=True)
+ run_disabled=True,
+ )
def testFlag_HasDisabledSuiteTest(self):
"""Tests the behavior of fail_fast and Disabled test suites."""
@@ -362,14 +407,16 @@ class GTestFailFastUnitTest(gtest_test_utils.TestCase):
failure_count=0,
skipped_count=0,
suppressed_count=5,
- run_disabled=False)
+ run_disabled=False,
+ )
self.assertNotFailFastBehavior(
test_suite='DISABLED_HasDisabledSuite',
passed_count=0,
failure_count=0,
skipped_count=0,
suppressed_count=5,
- run_disabled=False)
+ run_disabled=False,
+ )
def testFlag_HasDisabledSuiteRunDisabledTest(self):
"""Tests the behavior of fail_fast and Disabled test suites enabled."""
@@ -379,14 +426,16 @@ class GTestFailFastUnitTest(gtest_test_utils.TestCase):
failure_count=1,
skipped_count=3,
suppressed_count=0,
- run_disabled=True)
+ run_disabled=True,
+ )
self.assertNotFailFastBehavior(
test_suite='DISABLED_HasDisabledSuite',
passed_count=1,
failure_count=4,
skipped_count=0,
suppressed_count=0,
- run_disabled=True)
+ run_disabled=True,
+ )
if SUPPORTS_DEATH_TESTS:
@@ -397,13 +446,15 @@ class GTestFailFastUnitTest(gtest_test_utils.TestCase):
passed_count=1,
failure_count=1,
skipped_count=3,
- suppressed_count=0)
+ suppressed_count=0,
+ )
self.assertNotFailFastBehavior(
test_suite='HasDeathTest',
passed_count=1,
failure_count=4,
skipped_count=0,
- suppressed_count=0)
+ suppressed_count=0,
+ )
if __name__ == '__main__':
diff --git a/googletest/test/googletest-filepath-test.cc b/googletest/test/googletest-filepath-test.cc
index fe53f84..0a33d71 100644
--- a/googletest/test/googletest-filepath-test.cc
+++ b/googletest/test/googletest-filepath-test.cc
@@ -35,13 +35,15 @@
// This file is #included from gtest-internal.h.
// Do not #include this file anywhere else!
+#include <string>
+
#include "gtest/gtest.h"
#include "gtest/internal/gtest-filepath.h"
#include "src/gtest-internal-inl.h"
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
#include <windows.h> // NOLINT
-#elif GTEST_OS_WINDOWS
+#elif defined(GTEST_OS_WINDOWS)
#include <direct.h> // NOLINT
#endif // GTEST_OS_WINDOWS_MOBILE
@@ -49,7 +51,7 @@ namespace testing {
namespace internal {
namespace {
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
// Windows CE doesn't have the remove C function.
int remove(const char* path) {
@@ -78,7 +80,7 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) {
const FilePath cwd = FilePath::GetCurrentDir();
posix::ChDir(original_dir.c_str());
-#if GTEST_OS_WINDOWS || GTEST_OS_OS2
+#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_OS2)
// Skips the ":".
const char* const cwd_without_drive = strchr(cwd.c_str(), ':');
@@ -172,7 +174,7 @@ TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileNameForAlternateSeparator) {
// RemoveFileName "" -> "./"
TEST(RemoveFileNameTest, EmptyName) {
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
// On Windows CE, we use the root as the current directory.
EXPECT_EQ(GTEST_PATH_SEP_, FilePath("").RemoveFileName().string());
#else
@@ -355,7 +357,7 @@ TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) {
}
TEST(DirectoryTest, RootDirectoryExists) {
-#if GTEST_OS_WINDOWS // We are on Windows.
+#ifdef GTEST_OS_WINDOWS // We are on Windows.
char current_drive[_MAX_PATH]; // NOLINT
current_drive[0] = static_cast<char>(_getdrive() + 'A' - 1);
current_drive[1] = ':';
@@ -367,7 +369,7 @@ TEST(DirectoryTest, RootDirectoryExists) {
#endif // GTEST_OS_WINDOWS
}
-#if GTEST_OS_WINDOWS
+#ifdef 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.
@@ -385,7 +387,7 @@ TEST(DirectoryTest, RootOfWrongDriveDoesNotExists) {
}
#endif // GTEST_OS_WINDOWS
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
// Windows CE _does_ consider an empty directory to exist.
TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) {
EXPECT_FALSE(FilePath("").DirectoryExists());
@@ -393,7 +395,7 @@ TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) {
#endif // !GTEST_OS_WINDOWS_MOBILE
TEST(DirectoryTest, CurrentDirectoryExists) {
-#if GTEST_OS_WINDOWS // We are on Windows.
+#ifdef GTEST_OS_WINDOWS // We are on Windows.
#ifndef _WIN32_CE // Windows CE doesn't have a current directory.
EXPECT_TRUE(FilePath(".").DirectoryExists());
@@ -421,8 +423,13 @@ TEST(NormalizeTest, MultipleConsecutiveSeparatorsInMidstring) {
// "/bar" == //bar" == "///bar"
TEST(NormalizeTest, MultipleConsecutiveSeparatorsAtStringStart) {
EXPECT_EQ(GTEST_PATH_SEP_ "bar", FilePath(GTEST_PATH_SEP_ "bar").string());
+#ifdef GTEST_OS_WINDOWS
+ EXPECT_EQ(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar",
+ FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
+#else
EXPECT_EQ(GTEST_PATH_SEP_ "bar",
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
+#endif
EXPECT_EQ(
GTEST_PATH_SEP_ "bar",
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
@@ -613,7 +620,7 @@ TEST(FilePathTest, IsDirectory) {
TEST(FilePathTest, IsAbsolutePath) {
EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath());
EXPECT_FALSE(FilePath("").IsAbsolutePath());
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
EXPECT_TRUE(
FilePath("c:\\" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath());
@@ -621,6 +628,9 @@ TEST(FilePathTest, IsAbsolutePath) {
EXPECT_TRUE(
FilePath("c:/" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath());
+ EXPECT_TRUE(FilePath("d:/Windows").IsAbsolutePath());
+ EXPECT_TRUE(FilePath("\\\\Host\\Share").IsAbsolutePath());
+ EXPECT_TRUE(FilePath("\\\\Host\\Share\\Folder").IsAbsolutePath());
#else
EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
.IsAbsolutePath());
@@ -628,7 +638,7 @@ TEST(FilePathTest, IsAbsolutePath) {
}
TEST(FilePathTest, IsRootDirectory) {
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
EXPECT_TRUE(FilePath("a:\\").IsRootDirectory());
EXPECT_TRUE(FilePath("Z:/").IsRootDirectory());
EXPECT_TRUE(FilePath("e://").IsRootDirectory());
@@ -637,6 +647,16 @@ TEST(FilePathTest, IsRootDirectory) {
EXPECT_FALSE(FilePath("b:a").IsRootDirectory());
EXPECT_FALSE(FilePath("8:/").IsRootDirectory());
EXPECT_FALSE(FilePath("c|/").IsRootDirectory());
+ EXPECT_TRUE(FilePath("c:/").IsRootDirectory());
+ EXPECT_FALSE(FilePath("d:/Windows").IsRootDirectory());
+
+ // This is for backward compatibility, since callers (even in this library)
+ // have assumed IsRootDirectory() implies a trailing directory separator.
+ EXPECT_FALSE(FilePath("\\\\Host\\Share").IsRootDirectory());
+
+ EXPECT_TRUE(FilePath("\\\\Host\\Share\\").IsRootDirectory());
+ EXPECT_FALSE(FilePath("\\\\Host\\Share\\.").IsRootDirectory());
+ EXPECT_FALSE(FilePath("\\\\Host\\Share\\C$\\").IsRootDirectory());
#else
EXPECT_TRUE(FilePath("/").IsRootDirectory());
EXPECT_TRUE(FilePath("//").IsRootDirectory());
diff --git a/googletest/test/googletest-filter-unittest.py b/googletest/test/googletest-filter-unittest.py
index 2c4a1b1..f1f3c7a 100755
--- a/googletest/test/googletest-filter-unittest.py
+++ b/googletest/test/googletest-filter-unittest.py
@@ -42,6 +42,7 @@ we test that here also.
import os
import re
+
try:
from sets import Set as set # For Python 2.3 compatibility
except ImportError:
@@ -60,7 +61,8 @@ 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)'])
+ [sys.executable, '-c', "import os; print('EMPTY_VAR' in os.environ)"]
+ )
CAN_PASS_EMPTY_ENV = eval(child.output)
@@ -75,8 +77,8 @@ 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)'
- ])
+ [sys.executable, '-c', "import os; print('UNSET_VAR' not in os.environ)"]
+ )
CAN_UNSET_ENV = eval(child.output)
@@ -84,7 +86,7 @@ if sys.executable:
# 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)
+CAN_TEST_EMPTY_FILTER = CAN_PASS_EMPTY_ENV and CAN_UNSET_ENV
# The environment variable for specifying the test filters.
@@ -121,8 +123,10 @@ DISABLED_BANNER_REGEX = re.compile(r'^\[\s*DISABLED\s*\] (.*)')
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
+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 = [
@@ -134,7 +138,7 @@ PARAM_TESTS = [
'SeqQ/ParamTest.TestX/1',
'SeqQ/ParamTest.TestY/0',
'SeqQ/ParamTest.TestY/1',
- ]
+]
DISABLED_TESTS = [
'BarTest.DISABLED_TestFour',
@@ -143,29 +147,31 @@ DISABLED_TESTS = [
'DISABLED_FoobarTest.Test1',
'DISABLED_FoobarTest.DISABLED_Test2',
'DISABLED_FoobarbazTest.TestA',
- ]
+]
if SUPPORTS_DEATH_TESTS:
DEATH_TESTS = [
- 'HasDeathTest.Test1',
- 'HasDeathTest.Test2',
- ]
+ '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
+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
@@ -183,14 +189,15 @@ def SetEnvVar(env_var, value):
del environ[env_var]
-def RunAndReturnOutput(args = None):
+def RunAndReturnOutput(args=None):
"""Runs the test program and returns its output."""
- return gtest_test_utils.Subprocess([COMMAND] + (args or []),
- env=environ).output
+ return gtest_test_utils.Subprocess(
+ [COMMAND] + (args or []), env=environ
+ ).output
-def RunAndExtractTestList(args = None):
+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)
@@ -234,10 +241,13 @@ def InvokeWithModifiedEnv(extra_env, function, *args, **kwargs):
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)}
+ 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.
@@ -250,10 +260,10 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
"""Asserts that two sets are equal."""
for elem in lhs:
- self.assert_(elem in rhs, '%s in %s' % (elem, rhs))
+ self.assertTrue(elem in rhs, '%s in %s' % (elem, rhs))
for elem in rhs:
- self.assert_(elem in lhs, '%s in %s' % (elem, lhs))
+ self.assertTrue(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."""
@@ -285,13 +295,13 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
# 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
+ # pylint: disable=g-explicit-bool-comparison
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
+ # pylint: enable=g-explicit-bool-comparison
# Next, tests using the command line flag.
@@ -303,8 +313,14 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
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):
+ 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
@@ -316,9 +332,9 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
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.
+ 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)
@@ -328,7 +344,7 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
# 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
+ # pylint: disable=g-explicit-bool-comparison
if CAN_TEST_EMPTY_FILTER or gtest_filter != '':
SetEnvVar(FILTER_ENV_VAR, gtest_filter)
partition = []
@@ -340,7 +356,7 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
self.AssertPartitionIsValid(tests_to_run, partition)
SetEnvVar(FILTER_ENV_VAR, None)
- # pylint: enable-msg=C6403
+ # pylint: enable=g-explicit-bool-comparison
def RunAndVerifyAllowingDisabled(self, gtest_filter, tests_to_run):
"""Checks that the binary runs correct set of tests for the given filter.
@@ -372,8 +388,9 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
global param_tests_present
if param_tests_present is None:
- param_tests_present = PARAM_TEST_REGEX.search(
- RunAndReturnOutput()) is not None
+ param_tests_present = (
+ PARAM_TEST_REGEX.search(RunAndReturnOutput()) is not None
+ )
def testDefaultBehavior(self):
"""Tests the behavior of not specifying the filter."""
@@ -425,8 +442,9 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
BAZ_TESTS = ['BazTest.TestOne', 'BazTest.TestA', 'BazTest.TestB']
self.RunAndVerify('BazTest.*', BAZ_TESTS)
- self.RunAndVerifyAllowingDisabled('BazTest.*',
- BAZ_TESTS + ['BazTest.DISABLED_TestC'])
+ self.RunAndVerifyAllowingDisabled(
+ 'BazTest.*', BAZ_TESTS + ['BazTest.DISABLED_TestC']
+ )
def testFilterByTest(self):
"""Tests filtering by test name."""
@@ -437,38 +455,50 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
"""Select only the disabled tests to run."""
self.RunAndVerify('DISABLED_FoobarTest.Test1', [])
- self.RunAndVerifyAllowingDisabled('DISABLED_FoobarTest.Test1',
- ['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.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',
- ])
+ 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)
+ 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."""
@@ -478,23 +508,27 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
def testFilterWithoutDot(self):
"""Tests a filter that has no '.' in it."""
- self.RunAndVerify('*z*', [
- 'FooTest.Xyz',
-
- 'BazTest.TestOne',
- 'BazTest.TestA',
- 'BazTest.TestB',
- ])
+ 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',
- ])
+ self.RunAndVerify(
+ 'Foo*.*:*A*',
+ [
+ 'FooTest.Abc',
+ 'FooTest.Xyz',
+ 'BazTest.TestA',
+ ],
+ )
# An empty pattern + a non-empty one
self.RunAndVerify(':*A*', ['FooTest.Abc', 'BazTest.TestA'])
@@ -502,83 +536,109 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
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',
- ])
+ 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',
- ])
+ 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',
- ])
+ 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',
- ])
+ 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)
+ 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',
- ])
+ 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',
- ])
+ 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."""
@@ -593,38 +653,44 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
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))
+ shard_status_file = os.path.join(
+ gtest_test_utils.GetTempDir(), 'shard_status_file'
+ )
+ self.assertTrue(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))
+ self.assertTrue(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))
+ shard_status_file = os.path.join(
+ gtest_test_utils.GetTempDir(), 'shard_status_file2'
+ )
+ self.assertTrue(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])
+ 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))
+ self.assertTrue(
+ '[==========]' 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.assertTrue(os.path.exists(shard_status_file))
os.remove(shard_status_file)
def testDisabledBanner(self):
@@ -632,19 +698,25 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
make_filter = lambda s: ['--%s=%s' % (FILTER_FLAG, s)]
banners = RunAndExtractDisabledBannerList(make_filter('*'))
- self.AssertSetEqual(banners, [
- 'BarTest.DISABLED_TestFour', 'BarTest.DISABLED_TestFive',
- 'BazTest.DISABLED_TestC'
- ])
+ self.AssertSetEqual(
+ banners,
+ [
+ 'BarTest.DISABLED_TestFour',
+ 'BarTest.DISABLED_TestFive',
+ 'BazTest.DISABLED_TestC',
+ ],
+ )
banners = RunAndExtractDisabledBannerList(make_filter('Bar*'))
self.AssertSetEqual(
- banners, ['BarTest.DISABLED_TestFour', 'BarTest.DISABLED_TestFive'])
+ banners, ['BarTest.DISABLED_TestFour', 'BarTest.DISABLED_TestFive']
+ )
banners = RunAndExtractDisabledBannerList(make_filter('*-Bar*'))
self.AssertSetEqual(banners, ['BazTest.DISABLED_TestC'])
if SUPPORTS_DEATH_TESTS:
+
def testShardingWorksWithDeathTests(self):
"""Tests integration with death tests and sharding."""
@@ -652,19 +724,23 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
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])
+ ]
+
+ 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-global-environment-unittest.py b/googletest/test/googletest-global-environment-unittest.py
index 2657934..bd73a2e 100644
--- a/googletest/test/googletest-global-environment-unittest.py
+++ b/googletest/test/googletest-global-environment-unittest.py
@@ -42,10 +42,14 @@ from googletest.test import gtest_test_utils
def RunAndReturnOutput(args=None):
"""Runs the test program and returns its output."""
- return gtest_test_utils.Subprocess([
- gtest_test_utils.GetTestExecutablePath(
- 'googletest-global-environment-unittest_')
- ] + (args or [])).output
+ return gtest_test_utils.Subprocess(
+ [
+ gtest_test_utils.GetTestExecutablePath(
+ 'googletest-global-environment-unittest_'
+ )
+ ]
+ + (args or [])
+ ).output
class GTestGlobalEnvironmentUnitTest(gtest_test_utils.TestCase):
@@ -78,23 +82,25 @@ class GTestGlobalEnvironmentUnitTest(gtest_test_utils.TestCase):
'--gtest_recreate_environments_when_repeating=true',
])
- expected_pattern = ('(.|\n)*'
- r'Repeating all tests \(iteration 1\)'
- '(.|\n)*'
- 'Global test environment set-up.'
- '(.|\n)*'
- 'SomeTest.DoesFoo'
- '(.|\n)*'
- 'Global test environment tear-down'
- '(.|\n)*'
- r'Repeating all tests \(iteration 2\)'
- '(.|\n)*'
- 'Global test environment set-up.'
- '(.|\n)*'
- 'SomeTest.DoesFoo'
- '(.|\n)*'
- 'Global test environment tear-down'
- '(.|\n)*')
+ expected_pattern = (
+ '(.|\n)*'
+ r'Repeating all tests \(iteration 1\)'
+ '(.|\n)*'
+ 'Global test environment set-up.'
+ '(.|\n)*'
+ 'SomeTest.DoesFoo'
+ '(.|\n)*'
+ 'Global test environment tear-down'
+ '(.|\n)*'
+ r'Repeating all tests \(iteration 2\)'
+ '(.|\n)*'
+ 'Global test environment set-up.'
+ '(.|\n)*'
+ 'SomeTest.DoesFoo'
+ '(.|\n)*'
+ 'Global test environment tear-down'
+ '(.|\n)*'
+ )
self.assertRegex(txt, expected_pattern)
def testEnvironmentSetUpAndTornDownOnce(self):
@@ -102,28 +108,33 @@ class GTestGlobalEnvironmentUnitTest(gtest_test_utils.TestCase):
# By default the environment should only be set up and torn down once, at
# the start and end of the test respectively.
- txt = RunAndReturnOutput([
- '--gtest_repeat=2',
- ])
-
- expected_pattern = ('(.|\n)*'
- r'Repeating all tests \(iteration 1\)'
- '(.|\n)*'
- 'Global test environment set-up.'
- '(.|\n)*'
- 'SomeTest.DoesFoo'
- '(.|\n)*'
- r'Repeating all tests \(iteration 2\)'
- '(.|\n)*'
- 'SomeTest.DoesFoo'
- '(.|\n)*'
- 'Global test environment tear-down'
- '(.|\n)*')
+ txt = RunAndReturnOutput(
+ [
+ '--gtest_repeat=2',
+ ]
+ )
+
+ expected_pattern = (
+ '(.|\n)*'
+ r'Repeating all tests \(iteration 1\)'
+ '(.|\n)*'
+ 'Global test environment set-up.'
+ '(.|\n)*'
+ 'SomeTest.DoesFoo'
+ '(.|\n)*'
+ r'Repeating all tests \(iteration 2\)'
+ '(.|\n)*'
+ 'SomeTest.DoesFoo'
+ '(.|\n)*'
+ 'Global test environment tear-down'
+ '(.|\n)*'
+ )
self.assertRegex(txt, expected_pattern)
self.assertEqual(len(re.findall('Global test environment set-up', txt)), 1)
self.assertEqual(
- len(re.findall('Global test environment tear-down', txt)), 1)
+ len(re.findall('Global test environment tear-down', txt)), 1
+ )
if __name__ == '__main__':
diff --git a/googletest/test/googletest-json-outfiles-test.py b/googletest/test/googletest-json-outfiles-test.py
index 179283b..ff15722 100644
--- a/googletest/test/googletest-json-outfiles-test.py
+++ b/googletest/test/googletest-json-outfiles-test.py
@@ -40,93 +40,74 @@ 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'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'TestSomeProperties',
- u'file': u'gtest_xml_outfile1_test_.cc',
- u'line': 41,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'PropertyOne',
- u'SetUpProp': u'1',
- u'TestSomeProperty': u'1',
- u'TearDownProp': u'1',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'name': 'AllTests',
+ 'testsuites': [{
+ 'name': 'PropertyOne',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'TestSomeProperties',
+ 'file': 'gtest_xml_outfile1_test_.cc',
+ 'line': 41,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'PropertyOne',
+ 'SetUpProp': '1',
+ 'TestSomeProperty': '1',
+ 'TearDownProp': '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'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'TestSomeProperties',
- u'file': u'gtest_xml_outfile2_test_.cc',
- u'line': 41,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'timestamp': u'*',
- u'time': u'*',
- u'classname': u'PropertyTwo',
- u'SetUpProp': u'2',
- u'TestSomeProperty': u'2',
- u'TearDownProp': u'2',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'name': 'AllTests',
+ 'testsuites': [{
+ 'name': 'PropertyTwo',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'TestInt64ConvertibleProperties',
+ 'file': 'gtest_xml_outfile2_test_.cc',
+ 'line': 41,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'timestamp': '*',
+ 'time': '*',
+ 'classname': 'PropertyTwo',
+ 'SetUpProp': '2',
+ 'TestFloatProperty': '3.25',
+ 'TestDoubleProperty': '4.75',
+ 'TestSizetProperty': '5',
+ 'TestBoolProperty': 'true',
+ 'TestCharProperty': 'A',
+ 'TestInt16Property': '6',
+ 'TestInt32Property': '7',
+ 'TestInt64Property': '8',
+ 'TestEnumProperty': '9',
+ 'TestAtomicIntProperty': '10',
+ 'TearDownProp': '2',
}],
}],
}
@@ -139,8 +120,9 @@ class GTestJsonOutFilesTest(gtest_test_utils.TestCase):
# 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.output_dir_ = os.path.join(
+ gtest_test_utils.GetTempDir(), GTEST_OUTPUT_SUBDIR, ''
+ )
self.DeleteFilesAndDir()
def tearDown(self):
@@ -169,17 +151,20 @@ class GTestJsonOutFilesTest(gtest_test_utils.TestCase):
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)
+ p = gtest_test_utils.Subprocess(
+ command, working_dir=gtest_test_utils.GetTempDir()
+ )
+ self.assertTrue(p.exited)
+ self.assertEqual(0, p.exit_code)
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)
+ self.assertTrue(
+ 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:
diff --git a/googletest/test/googletest-json-output-unittest.py b/googletest/test/googletest-json-output-unittest.py
index e0fbe46..e955e7b 100644
--- a/googletest/test/googletest-json-output-unittest.py
+++ b/googletest/test/googletest-json-output-unittest.py
@@ -54,692 +54,573 @@ 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 = ''
+ STACK_TRACE_TEMPLATE = '\n'
EXPECTED_NON_EMPTY = {
- u'tests':
- 26,
- u'failures':
- 5,
- 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'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'Succeeds',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 51,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': 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'timestamp':
- u'*',
- u'testsuite': [{
- u'name':
- u'Fails',
- u'file':
- u'gtest_xml_output_unittest_.cc',
- u'line':
- 59,
- u'status':
- u'RUN',
- u'result':
- u'COMPLETED',
- u'time':
- u'*',
- u'timestamp':
- 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'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'DISABLED_test_not_run',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 66,
- u'status': u'NOTRUN',
- u'result': u'SUPPRESSED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'DisabledTest'
- }]
- }, {
- u'name':
- u'SkippedTest',
- u'tests':
- 3,
- u'failures':
- 1,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'Skipped',
- u'file': 'gtest_xml_output_unittest_.cc',
- u'line': 73,
- u'status': u'RUN',
- u'result': u'SKIPPED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'SkippedTest'
- }, {
- u'name': u'SkippedWithMessage',
- u'file': 'gtest_xml_output_unittest_.cc',
- u'line': 77,
- u'status': u'RUN',
- u'result': u'SKIPPED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'SkippedTest'
- }, {
- u'name':
- u'SkippedAfterFailure',
- u'file':
- 'gtest_xml_output_unittest_.cc',
- u'line':
- 81,
- u'status':
- u'RUN',
- u'result':
- u'COMPLETED',
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'classname':
- u'SkippedTest',
- 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'MixedResultTest',
- u'tests':
- 3,
- u'failures':
- 1,
- u'disabled':
- 1,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'Succeeds',
- u'file': 'gtest_xml_output_unittest_.cc',
- u'line': 86,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'MixedResultTest'
- }, {
- u'name':
- u'Fails',
- u'file':
- u'gtest_xml_output_unittest_.cc',
- u'line':
- 91,
- u'status':
- u'RUN',
- u'result':
- u'COMPLETED',
- u'time':
- u'*',
- u'timestamp':
- 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'file': u'gtest_xml_output_unittest_.cc',
- u'line': 96,
- u'status': u'NOTRUN',
- u'result': u'SUPPRESSED',
- u'time': u'*',
- u'timestamp': 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'timestamp':
- u'*',
- u'testsuite': [{
- u'name':
- u'OutputsCData',
- u'file':
- u'gtest_xml_output_unittest_.cc',
- u'line':
- 100,
- u'status':
- u'RUN',
- u'result':
- u'COMPLETED',
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'classname':
- u'XmlQuotingTest',
- u'failures': [{
- u'failure': u'gtest_xml_output_unittest_.cc:*\n'
- u'Failed\nXML output: <?xml encoding="utf-8">'
- u'<top><![CDATA[cdata text]]></top>' +
- 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'timestamp':
- u'*',
- u'testsuite': [{
- u'name':
- u'InvalidCharactersInMessage',
- u'file':
- u'gtest_xml_output_unittest_.cc',
- u'line':
- 107,
- u'status':
- u'RUN',
- u'result':
- u'COMPLETED',
- u'time':
- u'*',
- u'timestamp':
- 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'timestamp':
- u'*',
- u'SetUpTestSuite':
- u'yes',
- u'TearDownTestSuite':
- u'aye',
- u'testsuite': [{
- u'name': u'OneProperty',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 119,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'PropertyRecordingTest',
- u'key_1': u'1'
- }, {
- u'name': u'IntValuedProperty',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 123,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'PropertyRecordingTest',
- u'key_int': u'1'
- }, {
- u'name': u'ThreeProperties',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 127,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': 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'file': u'gtest_xml_output_unittest_.cc',
- u'line': 133,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': 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'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'RecordProperty',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 138,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'NoFixtureTest',
- u'key': u'1'
- }, {
- u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 151,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'NoFixtureTest',
- u'key_for_utility_int': u'1'
- }, {
- u'name': u'ExternalUtilityThatCallsRecordStringValuedProperty',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 155,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': 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'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'HasTypeParamAttribute',
- u'type_param': u'int',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 171,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': 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'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'HasTypeParamAttribute',
- u'type_param': u'long',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 171,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'TypedTest/1'
- }]
- }, {
- u'name':
- u'Single/TypeParameterizedTestSuite/0',
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'HasTypeParamAttribute',
- u'type_param': u'int',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 178,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'Single/TypeParameterizedTestSuite/0'
- }]
- }, {
- u'name':
- u'Single/TypeParameterizedTestSuite/1',
- u'tests':
- 1,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'HasTypeParamAttribute',
- u'type_param': u'long',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 178,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'Single/TypeParameterizedTestSuite/1'
- }]
- }, {
- u'name':
- u'Single/ValueParamTest',
- u'tests':
- 4,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'HasValueParamAttribute/0',
- u'value_param': u'33',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 162,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'Single/ValueParamTest'
- }, {
- u'name': u'HasValueParamAttribute/1',
- u'value_param': u'42',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 162,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'Single/ValueParamTest'
- }, {
- u'name': u'AnotherTestThatHasValueParamAttribute/0',
- u'value_param': u'33',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 163,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'Single/ValueParamTest'
- }, {
- u'name': u'AnotherTestThatHasValueParamAttribute/1',
- u'value_param': u'42',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 163,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'Single/ValueParamTest'
- }]
- }]
+ 'tests': 26,
+ 'failures': 5,
+ 'disabled': 2,
+ 'errors': 0,
+ 'timestamp': '*',
+ 'time': '*',
+ 'ad_hoc_property': '42',
+ 'name': 'AllTests',
+ 'testsuites': [
+ {
+ 'name': 'SuccessfulTest',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'Succeeds',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 51,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'SuccessfulTest',
+ }],
+ },
+ {
+ 'name': 'FailedTest',
+ 'tests': 1,
+ 'failures': 1,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'Fails',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 59,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'FailedTest',
+ 'failures': [{
+ 'failure': (
+ 'gtest_xml_output_unittest_.cc:*\n'
+ 'Expected equality of these values:\n'
+ ' 1\n 2'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ }],
+ }],
+ },
+ {
+ 'name': 'DisabledTest',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 1,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'DISABLED_test_not_run',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 66,
+ 'status': 'NOTRUN',
+ 'result': 'SUPPRESSED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'DisabledTest',
+ }],
+ },
+ {
+ 'name': 'SkippedTest',
+ 'tests': 3,
+ 'failures': 1,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [
+ {
+ 'name': 'Skipped',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 73,
+ 'status': 'RUN',
+ 'result': 'SKIPPED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'SkippedTest',
+ },
+ {
+ 'name': 'SkippedWithMessage',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 77,
+ 'status': 'RUN',
+ 'result': 'SKIPPED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'SkippedTest',
+ },
+ {
+ 'name': 'SkippedAfterFailure',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 81,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'SkippedTest',
+ 'failures': [{
+ 'failure': (
+ 'gtest_xml_output_unittest_.cc:*\n'
+ 'Expected equality of these values:\n'
+ ' 1\n 2'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ }],
+ },
+ ],
+ },
+ {
+ 'name': 'MixedResultTest',
+ 'tests': 3,
+ 'failures': 1,
+ 'disabled': 1,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [
+ {
+ 'name': 'Succeeds',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 86,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'MixedResultTest',
+ },
+ {
+ 'name': 'Fails',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 91,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'MixedResultTest',
+ 'failures': [
+ {
+ 'failure': (
+ 'gtest_xml_output_unittest_.cc:*\n'
+ 'Expected equality of these values:\n'
+ ' 1\n 2'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ },
+ {
+ 'failure': (
+ 'gtest_xml_output_unittest_.cc:*\n'
+ 'Expected equality of these values:\n'
+ ' 2\n 3'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ },
+ ],
+ },
+ {
+ 'name': 'DISABLED_test',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 96,
+ 'status': 'NOTRUN',
+ 'result': 'SUPPRESSED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'MixedResultTest',
+ },
+ ],
+ },
+ {
+ 'name': 'XmlQuotingTest',
+ 'tests': 1,
+ 'failures': 1,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'OutputsCData',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 100,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'XmlQuotingTest',
+ 'failures': [{
+ 'failure': (
+ 'gtest_xml_output_unittest_.cc:*\n'
+ 'Failed\nXML output: <?xml encoding="utf-8">'
+ '<top><![CDATA[cdata text]]></top>'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ }],
+ }],
+ },
+ {
+ 'name': 'InvalidCharactersTest',
+ 'tests': 1,
+ 'failures': 1,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'InvalidCharactersInMessage',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 107,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'InvalidCharactersTest',
+ 'failures': [{
+ 'failure': (
+ 'gtest_xml_output_unittest_.cc:*\n'
+ 'Failed\nInvalid characters in brackets'
+ ' [\x01\x02]'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ }],
+ }],
+ },
+ {
+ 'name': 'PropertyRecordingTest',
+ 'tests': 4,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'SetUpTestSuite': 'yes',
+ 'TearDownTestSuite': 'aye',
+ 'testsuite': [
+ {
+ 'name': 'OneProperty',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 119,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'PropertyRecordingTest',
+ 'key_1': '1',
+ },
+ {
+ 'name': 'IntValuedProperty',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 123,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'PropertyRecordingTest',
+ 'key_int': '1',
+ },
+ {
+ 'name': 'ThreeProperties',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 127,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'PropertyRecordingTest',
+ 'key_1': '1',
+ 'key_2': '2',
+ 'key_3': '3',
+ },
+ {
+ 'name': 'TwoValuesForOneKeyUsesLastValue',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 133,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'PropertyRecordingTest',
+ 'key_1': '2',
+ },
+ ],
+ },
+ {
+ 'name': 'NoFixtureTest',
+ 'tests': 3,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [
+ {
+ 'name': 'RecordProperty',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 138,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'NoFixtureTest',
+ 'key': '1',
+ },
+ {
+ 'name': 'ExternalUtilityThatCallsRecordIntValuedProperty',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 151,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'NoFixtureTest',
+ 'key_for_utility_int': '1',
+ },
+ {
+ 'name': (
+ 'ExternalUtilityThatCallsRecordStringValuedProperty'
+ ),
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 155,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'NoFixtureTest',
+ 'key_for_utility_string': '1',
+ },
+ ],
+ },
+ {
+ 'name': 'TypedTest/0',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'HasTypeParamAttribute',
+ 'type_param': 'int',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 171,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'TypedTest/0',
+ }],
+ },
+ {
+ 'name': 'TypedTest/1',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'HasTypeParamAttribute',
+ 'type_param': 'long',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 171,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'TypedTest/1',
+ }],
+ },
+ {
+ 'name': 'Single/TypeParameterizedTestSuite/0',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'HasTypeParamAttribute',
+ 'type_param': 'int',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 178,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'Single/TypeParameterizedTestSuite/0',
+ }],
+ },
+ {
+ 'name': 'Single/TypeParameterizedTestSuite/1',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'HasTypeParamAttribute',
+ 'type_param': 'long',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 178,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'Single/TypeParameterizedTestSuite/1',
+ }],
+ },
+ {
+ 'name': 'Single/ValueParamTest',
+ 'tests': 4,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [
+ {
+ 'name': 'HasValueParamAttribute/0',
+ 'value_param': '33',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 162,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'Single/ValueParamTest',
+ },
+ {
+ 'name': 'HasValueParamAttribute/1',
+ 'value_param': '42',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 162,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'Single/ValueParamTest',
+ },
+ {
+ 'name': 'AnotherTestThatHasValueParamAttribute/0',
+ 'value_param': '33',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 163,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'Single/ValueParamTest',
+ },
+ {
+ 'name': 'AnotherTestThatHasValueParamAttribute/1',
+ 'value_param': '42',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 163,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': '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'timestamp':
- u'*',
- u'testsuite': [{
- u'name': u'Succeeds',
- u'file': u'gtest_xml_output_unittest_.cc',
- u'line': 51,
- u'status': u'RUN',
- u'result': u'COMPLETED',
- u'time': u'*',
- u'timestamp': u'*',
- u'classname': u'SuccessfulTest',
- }]
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'name': 'AllTests',
+ 'ad_hoc_property': '42',
+ 'testsuites': [{
+ 'name': 'SuccessfulTest',
+ 'tests': 1,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': 'Succeeds',
+ 'file': 'gtest_xml_output_unittest_.cc',
+ 'line': 51,
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': 'SuccessfulTest',
+ }],
}],
}
EXPECTED_NO_TEST = {
- u'tests':
- 0,
- u'failures':
- 0,
- u'disabled':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'name':
- u'AllTests',
- u'testsuites': [{
- u'name':
- u'NonTestSuiteFailure',
- u'tests':
- 1,
- u'failures':
- 1,
- u'disabled':
- 0,
- u'skipped':
- 0,
- u'errors':
- 0,
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'testsuite': [{
- u'name':
- u'',
- u'status':
- u'RUN',
- u'result':
- u'COMPLETED',
- u'time':
- u'*',
- u'timestamp':
- u'*',
- u'classname':
- u'',
- u'failures': [{
- u'failure': u'gtest_no_test_unittest.cc:*\n'
- u'Expected equality of these values:\n'
- u' 1\n 2' + STACK_TRACE_TEMPLATE,
- u'type': u'',
- }]
- }]
+ 'tests': 0,
+ 'failures': 0,
+ 'disabled': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'name': 'AllTests',
+ 'testsuites': [{
+ 'name': 'NonTestSuiteFailure',
+ 'tests': 1,
+ 'failures': 1,
+ 'disabled': 0,
+ 'skipped': 0,
+ 'errors': 0,
+ 'time': '*',
+ 'timestamp': '*',
+ 'testsuite': [{
+ 'name': '',
+ 'status': 'RUN',
+ 'result': 'COMPLETED',
+ 'time': '*',
+ 'timestamp': '*',
+ 'classname': '',
+ 'failures': [{
+ 'failure': (
+ 'gtest_no_test_unittest.cc:*\n'
+ 'Expected equality of these values:\n'
+ ' 1\n 2'
+ + STACK_TRACE_TEMPLATE
+ ),
+ 'type': '',
+ }],
+ }],
}],
}
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
+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.
- """
+ """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.
@@ -775,16 +656,23 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
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)
+ '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)))
+ 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)
+ self.assertTrue(
+ time_delta < datetime.timedelta(seconds=600),
+ 'time_delta is %s' % time_delta,
+ )
def testDefaultOutputFile(self):
"""Verifies the default output file name.
@@ -792,10 +680,12 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
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)
+ output_file = os.path.join(
+ gtest_test_utils.GetTempDir(), GTEST_DEFAULT_OUTPUT_FILE
+ )
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
- 'gtest_no_test_unittest')
+ 'gtest_no_test_unittest'
+ )
try:
os.remove(output_file)
except OSError:
@@ -805,10 +695,11 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
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))
+ working_dir=gtest_test_utils.GetTempDir(),
+ )
+ self.assertTrue(p.exited)
+ self.assertEqual(0, p.exit_code)
+ self.assertTrue(os.path.isfile(output_file))
def testSuppressedJsonOutput(self):
"""Verifies that no JSON output is generated.
@@ -817,28 +708,34 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
shut down before RUN_ALL_TESTS is invoked.
"""
- json_path = os.path.join(gtest_test_utils.GetTempDir(),
- GTEST_PROGRAM_NAME + 'out.json')
+ 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']
+ 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))
+ '%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.assertTrue(p.exited)
+ self.assertEqual(
+ 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))
+ self.assertTrue(not os.path.isfile(json_path))
def testFilteredTestJsonOutput(self):
"""Verifies JSON output when a filter is applied.
@@ -847,8 +744,12 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
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])
+ 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.
@@ -860,30 +761,36 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
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')
+ 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
- )
+ 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))
+ self.assertTrue(
+ 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))
+ self.assertTrue(p.exited)
+ self.assertEqual(
+ 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):
+ 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
@@ -898,8 +805,9 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
extra_args: extra arguments to binary invocation.
"""
- actual = self._GetJsonOutput(gtest_prog_name, extra_args or [],
- expected_exit_code)
+ actual = self._GetJsonOutput(
+ gtest_prog_name, extra_args or [], expected_exit_code
+ )
self.assertEqual(expected, gtest_json_test_utils.normalize(actual))
diff --git a/googletest/test/googletest-list-tests-unittest.py b/googletest/test/googletest-list-tests-unittest.py
index 9d56883..977e57f 100755
--- a/googletest/test/googletest-list-tests-unittest.py
+++ b/googletest/test/googletest-list-tests-unittest.py
@@ -46,11 +46,14 @@ from googletest.test import gtest_test_utils
LIST_TESTS_FLAG = 'gtest_list_tests'
# Path to the googletest-list-tests-unittest_ program.
-EXE_PATH = gtest_test_utils.GetTestExecutablePath('googletest-list-tests-unittest_')
+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\.
+EXPECTED_OUTPUT_NO_FILTER_RE = re.compile(
+ r"""FooDeathTest\.
Test1
Foo\.
Bar1
@@ -90,11 +93,13 @@ MyInstantiation/ValueParamTest\.
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\.
+EXPECTED_OUTPUT_FILTER_FOO_RE = re.compile(
+ r"""FooDeathTest\.
Test1
Foo\.
Bar1
@@ -106,7 +111,8 @@ FooTest\.
Test1
DISABLED_Test2
Test3
-""")
+"""
+)
# Utilities.
@@ -114,8 +120,9 @@ FooTest\.
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
+ return gtest_test_utils.Subprocess(
+ [EXE_PATH] + args, capture_stderr=False
+ ).output
# The unit test.
@@ -125,17 +132,18 @@ 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
+ """Run googletest-list-tests-unittest_ and verify the output.
+
+ 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.
+ 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:
@@ -156,49 +164,61 @@ class GTestListTestsUnitTest(gtest_test_utils.TestCase):
output = Run(args)
if expected_output_re:
- self.assert_(
+ self.assertTrue(
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)))
+ '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_(
+ self.assertTrue(
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)))
+ '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)
+ 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)
+ 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')
+ 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."""
+ """Tests that --gtest_list_tests takes into account the filter flags.
+
+ 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*')
+ self.RunAndVerify(
+ flag_value='1',
+ expected_output_re=EXPECTED_OUTPUT_FILTER_FOO_RE,
+ other_flag='--gtest_filter=Foo*',
+ )
if __name__ == '__main__':
diff --git a/googletest/test/googletest-listener-test.cc b/googletest/test/googletest-listener-test.cc
index 89d01b3..654486d 100644
--- a/googletest/test/googletest-listener-test.cc
+++ b/googletest/test/googletest-listener-test.cc
@@ -38,13 +38,7 @@
#include "gtest/internal/custom/gtest.h"
using ::testing::AddGlobalTestEnvironment;
-using ::testing::Environment;
using ::testing::InitGoogleTest;
-using ::testing::Test;
-using ::testing::TestEventListener;
-using ::testing::TestInfo;
-using ::testing::TestPartResult;
-using ::testing::TestSuite;
using ::testing::UnitTest;
// Used by tests to register their events.
@@ -278,7 +272,7 @@ int main(int argc, char** argv) {
AddGlobalTestEnvironment(new EnvironmentInvocationCatcher);
- GTEST_CHECK_(events.size() == 0)
+ GTEST_CHECK_(events.empty())
<< "AddGlobalTestEnvironment should not generate any events itself.";
GTEST_FLAG_SET(repeat, 2);
diff --git a/googletest/test/googletest-message-test.cc b/googletest/test/googletest-message-test.cc
index 252a861..54e9d43 100644
--- a/googletest/test/googletest-message-test.cc
+++ b/googletest/test/googletest-message-test.cc
@@ -30,6 +30,9 @@
//
// Tests for the Message class.
+#include <sstream>
+#include <string>
+
#include "gtest/gtest-message.h"
#include "gtest/gtest.h"
diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc
index 1265c22..b712c06 100644
--- a/googletest/test/googletest-options-test.cc
+++ b/googletest/test/googletest-options-test.cc
@@ -36,13 +36,15 @@
// make-files on Windows and other platforms. Do not #include this file
// anywhere else!
+#include <string>
+
#include "gtest/gtest.h"
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
#include <windows.h>
-#elif GTEST_OS_WINDOWS
+#elif defined(GTEST_OS_WINDOWS)
#include <direct.h>
-#elif GTEST_OS_OS2
+#elif defined(GTEST_OS_OS2)
// For strcasecmp on OS/2
#include <strings.h>
#endif // GTEST_OS_WINDOWS_MOBILE
@@ -90,7 +92,7 @@ TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {
.string();
const std::string& output_file =
UnitTestOptions::GetAbsolutePathToOutputFile();
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
#else
EXPECT_EQ(expected_output_file, output_file.c_str());
@@ -99,19 +101,19 @@ TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {
TEST(OutputFileHelpersTest, GetCurrentExecutableName) {
const std::string exe_str = GetCurrentExecutableName().string();
-#if GTEST_OS_WINDOWS
+#ifdef 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_OS2
+#elif defined(GTEST_OS_OS2)
const bool success =
strcasecmp("googletest-options-test", exe_str.c_str()) == 0 ||
strcasecmp("gtest-options-ex_test", exe_str.c_str()) == 0 ||
strcasecmp("gtest_all_test", exe_str.c_str()) == 0 ||
strcasecmp("gtest_dll_test", exe_str.c_str()) == 0;
-#elif GTEST_OS_FUCHSIA
+#elif defined(GTEST_OS_FUCHSIA)
const bool success = exe_str == "app";
#else
const bool success =
@@ -121,7 +123,7 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) {
if (!success) FAIL() << "GetCurrentExecutableName() returns " << exe_str;
}
-#if !GTEST_OS_FUCHSIA
+#ifndef GTEST_OS_FUCHSIA
class XmlOutputChangeDirTest : public Test {
protected:
@@ -174,7 +176,7 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
.string();
const std::string& output_file =
UnitTestOptions::GetAbsolutePathToOutputFile();
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
#else
EXPECT_EQ(expected_output_file, output_file.c_str());
@@ -182,7 +184,7 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
}
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) {
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
GTEST_FLAG_SET(output, "xml:c:\\tmp\\filename.abc");
EXPECT_EQ(FilePath("c:\\tmp\\filename.abc").string(),
UnitTestOptions::GetAbsolutePathToOutputFile());
@@ -194,7 +196,7 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) {
}
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) {
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
const std::string path = "c:\\tmp\\";
#else
const std::string path = "/tmp/";
@@ -206,7 +208,7 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) {
const std::string& output_file =
UnitTestOptions::GetAbsolutePathToOutputFile();
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
#else
EXPECT_EQ(expected_output_file, output_file.c_str());
diff --git a/googletest/test/googletest-output-test.py b/googletest/test/googletest-output-test.py
index ff44483..6d80d53 100755
--- a/googletest/test/googletest-output-test.py
+++ b/googletest/test/googletest-output-test.py
@@ -63,20 +63,32 @@ PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('googletest-output-test_')
# '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_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_*'])
+ {},
+ [
+ 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.*'])
+ [
+ PROGRAM_PATH,
+ 'internal_skip_environment_and_ad_hoc_tests',
+ '--gtest_filter=PassingTest.*',
+ ],
+)
GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME)
@@ -100,23 +112,27 @@ def RemoveLocations(test_output):
'FILE_NAME:#: '.
"""
- return re.sub(r'.*[/\\]((googletest-output-test_|gtest).cc)(\:\d+|\(\d+\))\: ',
- r'\1:#: ', test_output)
+ 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)
+ 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)
+ return re.sub(r'Stack trace:(.|\n)*?\n', '', output)
def RemoveTime(output):
@@ -156,14 +172,12 @@ def NormalizeToCurrentPlatform(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)
+ 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)
@@ -175,18 +189,19 @@ def RemoveMatchingTests(test_output, pattern):
Args:
test_output: A string containing the test output.
- pattern: A regex string that matches names of test cases or
- tests to remove.
+ 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),
+ r'.*\[ RUN \] .*%s(.|\n)*?\[( FAILED | OK )\] .*%s.*\n'
+ % (pattern, pattern),
'',
- test_output)
+ test_output,
+ )
return re.sub(r'.*%s.*\n' % pattern, '', test_output)
@@ -205,8 +220,8 @@ def GetShellCommandOutput(env_cmd):
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.
+ 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.
@@ -222,13 +237,16 @@ def GetShellCommandOutput(env_cmd):
def GetCommandOutput(env_cmd):
- """Runs a command and returns its output with all file location
- info stripped off.
+ """Runs a command and returns 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.
+ 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. File
+ location info is stripped.
"""
# Disables exception pop-ups on Windows.
@@ -241,10 +259,12 @@ def GetCommandOutput(env_cmd):
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))
+ return (
+ GetCommandOutput(COMMAND_WITH_COLOR)
+ + GetCommandOutput(COMMAND_WITH_TIME)
+ + GetCommandOutput(COMMAND_WITH_DISABLED)
+ + GetCommandOutput(COMMAND_WITH_SHARDING)
+ )
test_list = GetShellCommandOutput(COMMAND_LIST_TESTS)
@@ -253,12 +273,16 @@ 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)
+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')
@@ -267,12 +291,13 @@ class GTestOutputTest(gtest_test_utils.TestCase):
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')
+ 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)
@@ -297,27 +322,42 @@ class GTestOutputTest(gtest_test_utils.TestCase):
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')))
+ 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))
+ RemoveTestCounts(normalized_actual)
+ )
normalized_golden = NormalizeToCurrentPlatform(
- RemoveTestCounts(self.RemoveUnsupportedTests(normalized_golden)))
+ 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)
+ 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)
@@ -334,11 +374,10 @@ if __name__ == '__main__':
golden_file.write(output.encode())
golden_file.close()
else:
- message = (
- """Unable to write a golden file when compiled in an environment
+ 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.""")
+Please build this test and generate the golden file using Blaze on Linux."""
sys.stderr.write(message)
sys.exit(1)
diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc
index c2f96d9..44d0fc1 100644
--- a/googletest/test/googletest-output-test_.cc
+++ b/googletest/test/googletest-output-test_.cc
@@ -39,11 +39,9 @@
#include "gtest/gtest.h"
#include "src/gtest-internal-inl.h"
-#if _MSC_VER
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */)
-#endif // _MSC_VER
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
using testing::ScopedFakeTestPartResultReporter;
using testing::TestPartResultArray;
@@ -249,7 +247,7 @@ TEST(SCOPED_TRACETest, CanBeRepeated) {
<< "contain trace point A, B, and D.";
}
-#if GTEST_IS_THREADSAFE
+#ifdef 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.
@@ -775,7 +773,7 @@ REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used);
// typedef ::testing::Types<char, int, unsigned int> MyTypes;
// INSTANTIATE_TYPED_TEST_SUITE_P(All, DetectNotInstantiatedTypesTest, MyTypes);
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
// We rely on the golden file to verify that tests whose test case
// name ends with DeathTest are run first.
@@ -853,7 +851,7 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailure) {
"failure.");
}
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
class ExpectFailureWithThreadsTest : public ExpectFailureTest {
protected:
@@ -1026,11 +1024,11 @@ int main(int argc, char** argv) {
std::count(argv, argv + argc,
std::string("internal_skip_environment_and_ad_hoc_tests")) > 0;
-#if GTEST_HAS_DEATH_TEST
- if (GTEST_FLAG_GET(internal_run_death_test) != "") {
+#ifdef GTEST_HAS_DEATH_TEST
+ if (!GTEST_FLAG_GET(internal_run_death_test).empty()) {
// Skip the usual output capturing if we're running as the child
// process of an threadsafe-style death test.
-#if GTEST_OS_WINDOWS
+#if defined(GTEST_OS_WINDOWS)
posix::FReopen("nul:", "w", stdout);
#else
posix::FReopen("/dev/null", "w", stdout);
@@ -1046,8 +1044,6 @@ int main(int argc, char** argv) {
// are registered, and torn down in the reverse order.
testing::AddGlobalTestEnvironment(new FooEnvironment);
testing::AddGlobalTestEnvironment(new BarEnvironment);
-#if _MSC_VER
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127
-#endif // _MSC_VER
return RunAllTests();
}
diff --git a/googletest/test/googletest-param-test-invalid-name1-test.py b/googletest/test/googletest-param-test-invalid-name1-test.py
index b8d609a..4886e49 100644
--- a/googletest/test/googletest-param-test-invalid-name1-test.py
+++ b/googletest/test/googletest-param-test-invalid-name1-test.py
@@ -44,7 +44,7 @@ def Assert(condition):
def TestExitCodeAndOutput(command):
"""Runs the given command and verifies its exit code and output."""
- err = ('Parameterized test name \'"InvalidWithQuotes"\' is invalid')
+ err = 'Parameterized test name \'"InvalidWithQuotes"\' is invalid'
p = gtest_test_utils.Subprocess(command)
Assert(p.terminated_by_signal)
diff --git a/googletest/test/googletest-param-test-invalid-name2-test.py b/googletest/test/googletest-param-test-invalid-name2-test.py
index d92fa06..bcd8ddf 100644
--- a/googletest/test/googletest-param-test-invalid-name2-test.py
+++ b/googletest/test/googletest-param-test-invalid-name2-test.py
@@ -44,7 +44,7 @@ def Assert(condition):
def TestExitCodeAndOutput(command):
"""Runs the given command and verifies its exit code and output."""
- err = ('Duplicate parameterized test name \'a\'')
+ err = "Duplicate parameterized test name 'a'"
p = gtest_test_utils.Subprocess(command)
Assert(p.terminated_by_signal)
@@ -58,5 +58,6 @@ 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-test.cc b/googletest/test/googletest-param-test-test.cc
index e3090ae..c9c5e78 100644
--- a/googletest/test/googletest-param-test-test.cc
+++ b/googletest/test/googletest-param-test-test.cc
@@ -40,6 +40,7 @@
#include <set>
#include <sstream>
#include <string>
+#include <tuple>
#include <vector>
#include "gtest/gtest.h"
@@ -51,6 +52,7 @@ using ::std::vector;
using ::testing::AddGlobalTestEnvironment;
using ::testing::Bool;
using ::testing::Combine;
+using ::testing::ConvertGenerator;
using ::testing::Message;
using ::testing::Range;
using ::testing::TestWithParam;
@@ -219,7 +221,7 @@ class DogAdder {
}
DogAdder operator+(const DogAdder& other) const {
Message msg;
- msg << value_.c_str() << other.value_.c_str();
+ msg << value_ << other.value_;
return DogAdder(msg.GetString().c_str());
}
bool operator<(const DogAdder& other) const { return value_ < other.value_; }
@@ -402,7 +404,7 @@ TEST(BoolTest, BoolWorks) {
TEST(CombineTest, CombineWithTwoParameters) {
const char* foo = "foo";
const char* bar = "bar";
- const ParamGenerator<std::tuple<const char*, int> > gen =
+ const ParamGenerator<std::tuple<const char*, int>> gen =
Combine(Values(foo, bar), Values(3, 4));
std::tuple<const char*, int> expected_values[] = {
@@ -413,7 +415,7 @@ TEST(CombineTest, CombineWithTwoParameters) {
// Tests that Combine() with three parameters generates the expected sequence.
TEST(CombineTest, CombineWithThreeParameters) {
- const ParamGenerator<std::tuple<int, int, int> > gen =
+ const ParamGenerator<std::tuple<int, int, int>> gen =
Combine(Values(0, 1), Values(3, 4), Values(5, 6));
std::tuple<int, int, int> expected_values[] = {
std::make_tuple(0, 3, 5), std::make_tuple(0, 3, 6),
@@ -427,7 +429,7 @@ TEST(CombineTest, CombineWithThreeParameters) {
// 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<std::tuple<int, int> > gen =
+ const ParamGenerator<std::tuple<int, int>> gen =
Combine(Values(42), Values(0, 1));
std::tuple<int, int> expected_values[] = {std::make_tuple(42, 0),
@@ -439,7 +441,7 @@ TEST(CombineTest, CombineWithFirstParameterSingleValue) {
// 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<std::tuple<int, int> > gen =
+ const ParamGenerator<std::tuple<int, int>> gen =
Combine(Values(0, 1), Values(42));
std::tuple<int, int> expected_values[] = {std::make_tuple(0, 42),
@@ -450,7 +452,7 @@ TEST(CombineTest, CombineWithSecondParameterSingleValue) {
// Tests that when the first parameter produces an empty sequence,
// Combine() produces an empty sequence, too.
TEST(CombineTest, CombineWithFirstParameterEmptyRange) {
- const ParamGenerator<std::tuple<int, int> > gen =
+ const ParamGenerator<std::tuple<int, int>> gen =
Combine(Range(0, 0), Values(0, 1));
VerifyGeneratorIsEmpty(gen);
}
@@ -458,7 +460,7 @@ TEST(CombineTest, CombineWithFirstParameterEmptyRange) {
// Tests that when the second parameter produces an empty sequence,
// Combine() produces an empty sequence, too.
TEST(CombineTest, CombineWithSecondParameterEmptyRange) {
- const ParamGenerator<std::tuple<int, int> > gen =
+ const ParamGenerator<std::tuple<int, int>> gen =
Combine(Values(0, 1), Range(1, 1));
VerifyGeneratorIsEmpty(gen);
}
@@ -469,7 +471,7 @@ TEST(CombineTest, CombineWithMaxNumberOfParameters) {
const char* foo = "foo";
const char* bar = "bar";
const ParamGenerator<
- std::tuple<const char*, int, int, int, int, int, int, int, int, int> >
+ std::tuple<const char*, int, int, int, int, int, int, int, int, int>>
gen =
Combine(Values(foo, bar), Values(1), Values(2), Values(3), Values(4),
Values(5), Values(6), Values(7), Values(8), Values(9));
@@ -497,11 +499,11 @@ class NonDefaultConstructAssignString {
};
TEST(CombineTest, NonDefaultConstructAssign) {
- const ParamGenerator<std::tuple<int, NonDefaultConstructAssignString> > gen =
+ const ParamGenerator<std::tuple<int, NonDefaultConstructAssignString>> gen =
Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"),
NonDefaultConstructAssignString("B")));
- ParamGenerator<std::tuple<int, NonDefaultConstructAssignString> >::iterator
+ ParamGenerator<std::tuple<int, NonDefaultConstructAssignString>>::iterator
it = gen.begin();
EXPECT_EQ(0, std::get<0>(*it));
@@ -523,6 +525,64 @@ TEST(CombineTest, NonDefaultConstructAssign) {
EXPECT_TRUE(it == gen.end());
}
+template <typename T>
+class ConstructFromT {
+ public:
+ explicit ConstructFromT(const T& t) : t_(t) {}
+ template <typename... Args,
+ typename std::enable_if<sizeof...(Args) != 1, int>::type = 0>
+ ConstructFromT(Args&&... args) : t_(std::forward<Args>(args)...) {}
+
+ bool operator==(const ConstructFromT& other) const { return other.t_ == t_; }
+
+ const T& get() const { return t_; }
+
+ private:
+ T t_;
+};
+
+TEST(ConvertTest, CombineWithTwoParameters) {
+ const char* foo = "foo";
+ const char* bar = "bar";
+ const ParamGenerator<ConstructFromT<std::tuple<const char*, int>>> gen =
+ ConvertGenerator<std::tuple<const char*, int>>(
+ Combine(Values(foo, bar), Values(3, 4)));
+
+ ConstructFromT<std::tuple<const char*, int>> expected_values[] = {
+ {foo, 3}, {foo, 4}, {bar, 3}, {bar, 4}};
+ VerifyGenerator(gen, expected_values);
+}
+
+TEST(ConvertTest, NonDefaultConstructAssign) {
+ const ParamGenerator<
+ ConstructFromT<std::tuple<int, NonDefaultConstructAssignString>>>
+ gen = ConvertGenerator<std::tuple<int, NonDefaultConstructAssignString>>(
+ Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"),
+ NonDefaultConstructAssignString("B"))));
+
+ ParamGenerator<ConstructFromT<
+ std::tuple<int, NonDefaultConstructAssignString>>>::iterator it =
+ gen.begin();
+
+ EXPECT_EQ(0, std::get<0>(it->get()));
+ EXPECT_EQ("A", std::get<1>(it->get()).str());
+ ++it;
+
+ EXPECT_EQ(0, std::get<0>(it->get()));
+ EXPECT_EQ("B", std::get<1>(it->get()).str());
+ ++it;
+
+ EXPECT_EQ(1, std::get<0>(it->get()));
+ EXPECT_EQ("A", std::get<1>(it->get()).str());
+ ++it;
+
+ EXPECT_EQ(1, std::get<0>(it->get()));
+ EXPECT_EQ("B", std::get<1>(it->get()).str());
+ ++it;
+
+ EXPECT_TRUE(it == gen.end());
+}
+
// Tests that an generator produces correct sequence after being
// assigned from another generator.
TEST(ParamGeneratorTest, AssignmentWorks) {
diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc
index c20dfa4..1ba3f50 100644
--- a/googletest/test/googletest-port-test.cc
+++ b/googletest/test/googletest-port-test.cc
@@ -32,13 +32,14 @@
#include "gtest/internal/gtest-port.h"
-#if GTEST_OS_MAC
+#ifdef GTEST_OS_MAC
#include <time.h>
#endif // GTEST_OS_MAC
#include <chrono> // NOLINT
#include <list>
#include <memory>
+#include <string>
#include <thread> // NOLINT
#include <utility> // For std::pair and std::make_pair.
#include <vector>
@@ -280,9 +281,11 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(nullptr, -1));
}
-#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \
- GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
- GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD
+#if defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || \
+ defined(GTEST_OS_QNX) || defined(GTEST_OS_FUCHSIA) || \
+ defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
+ defined(GTEST_OS_GNU_KFREEBSD) || defined(GTEST_OS_NETBSD) || \
+ defined(GTEST_OS_OPENBSD) || defined(GTEST_OS_GNU_HURD)
void* ThreadFunc(void* data) {
internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
mutex->Lock();
@@ -358,7 +361,7 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
const char regex[] =
#ifdef _MSC_VER
"googletest-port-test\\.cc\\(\\d+\\):"
-#elif GTEST_USES_POSIX_RE
+#elif defined(GTEST_USES_POSIX_RE)
"googletest-port-test\\.cc:[0-9]+"
#else
"googletest-port-test\\.cc:\\d+"
@@ -369,7 +372,7 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
regex);
}
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
EXPECT_EXIT(
@@ -387,7 +390,7 @@ TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
// the platform. The test will produce compiler errors in case of failure.
// For simplicity, we only cover the most important platforms here.
TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
EXPECT_TRUE(GTEST_USES_RE2);
#elif GTEST_HAS_POSIX_RE
EXPECT_TRUE(GTEST_USES_POSIX_RE);
@@ -396,7 +399,7 @@ TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
#endif
}
-#if GTEST_USES_POSIX_RE
+#ifdef GTEST_USES_POSIX_RE
template <typename Str>
class RETest : public ::testing::Test {};
@@ -453,7 +456,7 @@ TYPED_TEST(RETest, PartialMatchWorks) {
EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
}
-#elif GTEST_USES_SIMPLE_RE
+#elif defined(GTEST_USES_SIMPLE_RE)
TEST(IsInSetTest, NulCharIsNotInAnySet) {
EXPECT_FALSE(IsInSet('\0', ""));
@@ -915,7 +918,7 @@ TEST(RETest, PartialMatchWorks) {
#endif // GTEST_USES_POSIX_RE
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
TEST(CaptureTest, CapturesStdout) {
CaptureStdout();
@@ -1008,7 +1011,7 @@ TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
}
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
void AddTwo(int* param) { *param += 2; }
@@ -1063,7 +1066,7 @@ class AtomicCounterWithMutex {
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
-#elif GTEST_OS_WINDOWS
+#elif defined(GTEST_OS_WINDOWS)
// On Windows, performing an interlocked access puts up a memory barrier.
volatile LONG dummy = 0;
::InterlockedIncrement(&dummy);
@@ -1101,9 +1104,9 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
// 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(
+ counting_threads[i] = std::make_unique<ThreadType>(
&CountingThreadFunc, make_pair(&locked_counter, kCycleCount),
- &threads_can_start));
+ &threads_can_start);
}
threads_can_start.Notify();
for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join();
@@ -1145,14 +1148,14 @@ class DestructorCall {
public:
DestructorCall() {
invoked_ = false;
-#if GTEST_OS_WINDOWS
+#ifdef 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
+#ifdef GTEST_OS_WINDOWS
if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
return false;
#endif
@@ -1161,7 +1164,7 @@ class DestructorCall {
void ReportDestroyed() {
invoked_ = true;
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
::SetEvent(wait_event_.Get());
#endif
}
@@ -1177,7 +1180,7 @@ class DestructorCall {
private:
bool invoked_;
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
AutoHandle wait_event_;
#endif
static std::vector<DestructorCall*>* const list_;
@@ -1277,12 +1280,12 @@ TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
#endif // GTEST_IS_THREADSAFE
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
TEST(WindowsTypesTest, HANDLEIsVoidStar) {
StaticAssertTypeEq<HANDLE, void*>();
}
-#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
+#if defined(GTEST_OS_WINDOWS_MINGW) && !defined(__MINGW64_VERSION_MAJOR)
TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) {
StaticAssertTypeEq<CRITICAL_SECTION, _CRITICAL_SECTION>();
}
diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc
index acfecf9..7fa82d0 100644
--- a/googletest/test/googletest-printers-test.cc
+++ b/googletest/test/googletest-printers-test.cc
@@ -37,6 +37,7 @@
#include <cstring>
#include <deque>
#include <forward_list>
+#include <functional>
#include <limits>
#include <list>
#include <map>
@@ -193,6 +194,11 @@ OutputStream& operator<<(OutputStream& os,
return os;
}
+struct StreamableInLocal {};
+void operator<<(::std::ostream& os, const StreamableInLocal& /* x */) {
+ os << "StreamableInLocal";
+}
+
// A user-defined streamable but recursively-defined container type in
// a user namespace, it mimics therefore std::filesystem::path or
// boost::filesystem::path.
@@ -260,7 +266,6 @@ using ::std::set;
using ::std::vector;
using ::testing::PrintToString;
using ::testing::internal::FormatForComparisonFailureMessage;
-using ::testing::internal::ImplicitCast_;
using ::testing::internal::NativeArray;
using ::testing::internal::RelationToSourceReference;
using ::testing::internal::Strings;
@@ -354,7 +359,7 @@ TEST(PrintCharTest, Char16) { EXPECT_EQ("U+0041", Print(u'A')); }
TEST(PrintCharTest, Char32) { EXPECT_EQ("U+0041", Print(U'A')); }
-#ifdef __cpp_char8_t
+#ifdef __cpp_lib_char8_t
TEST(PrintCharTest, Char8) { EXPECT_EQ("U+0041", Print(u8'A')); }
#endif
@@ -407,7 +412,7 @@ TEST(PrintBuiltInTypeTest, Integer) {
Print(std::numeric_limits<uint64_t>::max())); // uint64
EXPECT_EQ("-9223372036854775808",
Print(std::numeric_limits<int64_t>::min())); // int64
-#ifdef __cpp_char8_t
+#ifdef __cpp_lib_char8_t
EXPECT_EQ("U+0000",
Print(std::numeric_limits<char8_t>::min())); // char8_t
EXPECT_EQ("U+00FF",
@@ -426,7 +431,7 @@ TEST(PrintBuiltInTypeTest, Integer) {
// Size types.
TEST(PrintBuiltInTypeTest, Size_t) {
EXPECT_EQ("1", Print(sizeof('a'))); // size_t.
-#if !GTEST_OS_WINDOWS
+#ifndef GTEST_OS_WINDOWS
// Windows has no ssize_t type.
EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2))); // ssize_t.
#endif // !GTEST_OS_WINDOWS
@@ -452,7 +457,15 @@ TEST(PrintBuiltInTypeTest, Int128) {
// Floating-points.
TEST(PrintBuiltInTypeTest, FloatingPoints) {
- EXPECT_EQ("1.5", Print(1.5f)); // float
+ // float (32-bit precision)
+ EXPECT_EQ("1.5", Print(1.5f));
+
+ EXPECT_EQ("1.0999999", Print(1.09999990f));
+ EXPECT_EQ("1.1", Print(1.10000002f));
+ EXPECT_EQ("1.10000014", Print(1.10000014f));
+ EXPECT_EQ("9e+09", Print(9e9f));
+
+ // double
EXPECT_EQ("-2.5", Print(-2.5)); // double
}
@@ -505,7 +518,7 @@ TEST(PrintCStringTest, EscapesProperly) {
Print(p));
}
-#ifdef __cpp_char8_t
+#ifdef __cpp_lib_char8_t
// const char8_t*.
TEST(PrintU8StringTest, Const) {
const char8_t* p = u8"界";
@@ -802,7 +815,7 @@ TEST(PrintArrayTest, CharArrayWithTerminatingNul) {
EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a));
}
-#ifdef __cpp_char8_t
+#ifdef __cpp_lib_char8_t
// char_t array without terminating NUL.
TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) {
// Array a contains '\0' in the middle and doesn't end with '\0'.
@@ -922,7 +935,7 @@ TEST(PrintWideStringTest, StringAmbiguousHex) {
}
#endif // GTEST_HAS_STD_WSTRING
-#ifdef __cpp_char8_t
+#ifdef __cpp_lib_char8_t
TEST(PrintStringTest, U8String) {
std::u8string str = u8"Hello, 世界";
EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
@@ -1604,6 +1617,23 @@ TEST(PrintToStringTest, ContainsNonLatin) {
"\n As Text: \"From ä — ẑ\"");
}
+TEST(PrintToStringTest, PrintStreamableInLocal) {
+ EXPECT_STREQ("StreamableInLocal",
+ PrintToString(foo::StreamableInLocal()).c_str());
+}
+
+TEST(PrintToStringTest, PrintReferenceToStreamableInLocal) {
+ foo::StreamableInLocal s;
+ std::reference_wrapper<foo::StreamableInLocal> r(s);
+ EXPECT_STREQ("StreamableInLocal", PrintToString(r).c_str());
+}
+
+TEST(PrintToStringTest, PrintReferenceToStreamableInGlobal) {
+ StreamableInGlobal s;
+ std::reference_wrapper<StreamableInGlobal> r(s);
+ EXPECT_STREQ("StreamableInGlobal", PrintToString(r).c_str());
+}
+
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
@@ -1765,7 +1795,8 @@ TEST(UniversalPrintTest, SmartPointers) {
std::shared_ptr<int> p3(new int(1979));
EXPECT_EQ("(ptr = " + PrintPointer(p3.get()) + ", value = 1979)",
PrintToString(p3));
-#if __cpp_lib_shared_ptr_arrays >= 201611L
+#if defined(__cpp_lib_shared_ptr_arrays) && \
+ (__cpp_lib_shared_ptr_arrays >= 201611L)
std::shared_ptr<int[]> p4(new int[2]);
EXPECT_EQ("(" + PrintPointer(p4.get()) + ")", PrintToString(p4));
#endif
@@ -1784,7 +1815,8 @@ TEST(UniversalPrintTest, SmartPointers) {
EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int>()));
EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int>()));
EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile const int>()));
-#if __cpp_lib_shared_ptr_arrays >= 201611L
+#if defined(__cpp_lib_shared_ptr_arrays) && \
+ (__cpp_lib_shared_ptr_arrays >= 201611L)
EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int[]>()));
EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int[]>()));
EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int[]>()));
diff --git a/googletest/test/googletest-setuptestsuite-test.py b/googletest/test/googletest-setuptestsuite-test.py
index 9d1fd02..899531f 100755
--- a/googletest/test/googletest-setuptestsuite-test.py
+++ b/googletest/test/googletest-setuptestsuite-test.py
@@ -34,7 +34,8 @@
from googletest.test import gtest_test_utils
COMMAND = gtest_test_utils.GetTestExecutablePath(
- 'googletest-setuptestsuite-test_')
+ 'googletest-setuptestsuite-test_'
+)
class GTestSetUpTestSuiteTest(gtest_test_utils.TestCase):
@@ -44,11 +45,14 @@ class GTestSetUpTestSuiteTest(gtest_test_utils.TestCase):
self.assertNotEqual(p.exit_code, 0, msg=p.output)
self.assertIn(
- '[ FAILED ] SetupFailTest: SetUpTestSuite or TearDownTestSuite\n'
- '[ FAILED ] TearDownFailTest: SetUpTestSuite or TearDownTestSuite\n'
- '\n'
- ' 2 FAILED TEST SUITES\n',
- p.output)
+ (
+ '[ FAILED ] SetupFailTest: SetUpTestSuite or TearDownTestSuite\n['
+ ' FAILED ] TearDownFailTest: SetUpTestSuite or'
+ ' TearDownTestSuite\n\n 2 FAILED TEST SUITES\n'
+ ),
+ p.output,
+ )
+
if __name__ == '__main__':
gtest_test_utils.Main()
diff --git a/googletest/test/googletest-shuffle-test.py b/googletest/test/googletest-shuffle-test.py
index 9d2adc1..61e3a15 100755
--- a/googletest/test/googletest-shuffle-test.py
+++ b/googletest/test/googletest-shuffle-test.py
@@ -130,38 +130,50 @@ def CalculateTestLists():
if not ALL_TESTS:
ALL_TESTS.extend(
- GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0])
+ GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0]
+ )
if not ACTIVE_TESTS:
ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [])[0])
if not FILTERED_TESTS:
FILTERED_TESTS.extend(
- GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0])
+ GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0]
+ )
if not SHARDED_TESTS:
SHARDED_TESTS.extend(
- GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',
- SHARD_INDEX_ENV_VAR: '1'},
- [])[0])
+ 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])
+ SHUFFLED_ALL_TESTS.extend(
+ GetTestsForAllIterations(
+ {}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)]
+ )[0]
+ )
if not SHUFFLED_ACTIVE_TESTS:
- SHUFFLED_ACTIVE_TESTS.extend(GetTestsForAllIterations(
- {}, [ShuffleFlag(), RandomSeedFlag(1)])[0])
+ 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])
+ 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])
+ GetTestsForAllIterations(
+ {TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '1'},
+ [ShuffleFlag(), RandomSeedFlag(1)],
+ )[0]
+ )
class GTestShuffleUnitTest(gtest_test_utils.TestCase):
@@ -177,66 +189,91 @@ class GTestShuffleUnitTest(gtest_test_utils.TestCase):
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)
+ self.assertTrue(SHUFFLED_ALL_TESTS != ALL_TESTS, SHUFFLED_ALL_TESTS)
+ self.assertTrue(
+ SHUFFLED_ACTIVE_TESTS != ACTIVE_TESTS, SHUFFLED_ACTIVE_TESTS
+ )
+ self.assertTrue(
+ SHUFFLED_FILTERED_TESTS != FILTERED_TESTS, SHUFFLED_FILTERED_TESTS
+ )
+ self.assertTrue(
+ 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_(
+ self.assertTrue(
+ GetTestCases(SHUFFLED_ALL_TESTS) != GetTestCases(ALL_TESTS),
+ GetTestCases(SHUFFLED_ALL_TESTS),
+ )
+ self.assertTrue(
GetTestCases(SHUFFLED_ACTIVE_TESTS) != GetTestCases(ACTIVE_TESTS),
- GetTestCases(SHUFFLED_ACTIVE_TESTS))
- self.assert_(
+ GetTestCases(SHUFFLED_ACTIVE_TESTS),
+ )
+ self.assertTrue(
GetTestCases(SHUFFLED_FILTERED_TESTS) != GetTestCases(FILTERED_TESTS),
- GetTestCases(SHUFFLED_FILTERED_TESTS))
- self.assert_(
+ GetTestCases(SHUFFLED_FILTERED_TESTS),
+ )
+ self.assertTrue(
GetTestCases(SHUFFLED_SHARDED_TESTS) != GetTestCases(SHARDED_TESTS),
- GetTestCases(SHUFFLED_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,))
+ 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,))
+ 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,))
+ 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,))
+ 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,))
+ self.assertTrue(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,))
+ self.assertTrue(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,))
+ self.assertTrue(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,))
+ self.assertTrue(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,))
+ self.assertTrue(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,))
+ self.assertTrue(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,))
+ self.assertTrue(
+ 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,))
+ self.assertTrue(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,))
+ self.assertTrue(
+ not non_death_test_found,
+ '%s appears after a non-death test' % (test,),
+ )
else:
non_death_test_found = True
@@ -246,9 +283,11 @@ class GTestShuffleUnitTest(gtest_test_utils.TestCase):
[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))
+ 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)
@@ -262,56 +301,71 @@ class GTestShuffleUnitTest(gtest_test_utils.TestCase):
# 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.
+ # pylint: disable-next=unbalanced-tuple-unpacking
[tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (
GetTestsForAllIterations(
- {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))
+ {}, [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)])
+ tests_with_seed1 = GetTestsForAllIterations(
+ {}, [ShuffleFlag(), RandomSeedFlag(1)]
+ )[0]
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)])
+ tests_with_seed2 = GetTestsForAllIterations(
+ {}, [ShuffleFlag(), RandomSeedFlag(2)]
+ )[0]
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)])
+ tests_with_seed3 = GetTestsForAllIterations(
+ {}, [ShuffleFlag(), RandomSeedFlag(3)]
+ )[0]
self.assertEqual(tests_in_iteration3, tests_with_seed3)
def testShuffleGeneratesNewOrderInEachIteration(self):
+ # pylint: disable-next=unbalanced-tuple-unpacking
[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)
+ {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]
+ )
+ )
+
+ self.assertTrue(
+ tests_in_iteration1 != tests_in_iteration2, tests_in_iteration1
+ )
+ self.assertTrue(
+ tests_in_iteration1 != tests_in_iteration3, tests_in_iteration1
+ )
+ self.assertTrue(
+ 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)])
+ tests1 = GetTestsForAllIterations(
+ {TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '0'},
+ [ShuffleFlag(), RandomSeedFlag(1)],
+ )[0]
+ tests2 = GetTestsForAllIterations(
+ {TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '1'},
+ [ShuffleFlag(), RandomSeedFlag(20)],
+ )[0]
+ tests3 = GetTestsForAllIterations(
+ {TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '2'},
+ [ShuffleFlag(), RandomSeedFlag(25)],
+ )[0]
sorted_sharded_tests = tests1 + tests2 + tests3
sorted_sharded_tests.sort()
sorted_active_tests = []
@@ -319,5 +373,6 @@ class GTestShuffleUnitTest(gtest_test_utils.TestCase):
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
index a14e22f..b570c48 100644
--- a/googletest/test/googletest-shuffle-test_.cc
+++ b/googletest/test/googletest-shuffle-test_.cc
@@ -35,7 +35,6 @@ namespace {
using ::testing::EmptyTestEventListener;
using ::testing::InitGoogleTest;
-using ::testing::Message;
using ::testing::Test;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
diff --git a/googletest/test/googletest-throw-on-failure-test.py b/googletest/test/googletest-throw-on-failure-test.py
index 772bbc5..106b004 100755
--- a/googletest/test/googletest-throw-on-failure-test.py
+++ b/googletest/test/googletest-throw-on-failure-test.py
@@ -47,15 +47,22 @@ 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_')
+ 'googletest-throw-on-failure-test_'
+)
# Utilities.
def SetEnvVar(env_var, value):
- """Sets an environment variable to a given value; unsets it when the
+ """Sets an environment variable.
+
+ Sets an environment variable to a given value; unsets it when the
given value is None.
+
+ Args:
+ env_var: environment variable.
+ value: value to set.
"""
env_var = env_var.upper()
@@ -78,14 +85,16 @@ 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
+ """Runs googletest-throw-on-failure-test_ and verifies its behavior.
+
+ 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.
+ 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 if and only if the program is expected to fail.
"""
@@ -116,11 +125,16 @@ class ThrowOnFailureTest(gtest_test_utils.TestCase):
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)
+ 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.assertTrue(failed == should_fail, msg)
def testDefaultBehavior(self):
"""Tests the behavior of the default mode."""
@@ -130,38 +144,22 @@ class ThrowOnFailureTest(gtest_test_utils.TestCase):
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)
+ 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)
+ 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)
+ 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__':
diff --git a/googletest/test/googletest-uninitialized-test.py b/googletest/test/googletest-uninitialized-test.py
index 73c9176..e5af7c8 100755
--- a/googletest/test/googletest-uninitialized-test.py
+++ b/googletest/test/googletest-uninitialized-test.py
@@ -33,7 +33,9 @@
from googletest.test import gtest_test_utils
-COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-uninitialized-test_')
+COMMAND = gtest_test_utils.GetTestExecutablePath(
+ 'googletest-uninitialized-test_'
+)
def Assert(condition):
@@ -54,11 +56,12 @@ def TestExitCodeAndOutput(command):
# 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('IMPORTANT NOTICE' in p.output)
Assert('InitGoogleTest' in p.output)
class GTestUninitializedTest(gtest_test_utils.TestCase):
+
def testExitCodeAndOutput(self):
TestExitCodeAndOutput(COMMAND)
diff --git a/googletest/test/gtest-typed-test_test.cc b/googletest/test/gtest-typed-test_test.cc
index af23f86..0cc8b21 100644
--- a/googletest/test/gtest-typed-test_test.cc
+++ b/googletest/test/gtest-typed-test_test.cc
@@ -30,14 +30,13 @@
#include "test/gtest-typed-test_test.h"
#include <set>
+#include <string>
#include <type_traits>
#include <vector>
#include "gtest/gtest.h"
-#if _MSC_VER
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */)
-#endif // _MSC_VER
using testing::Test;
@@ -420,3 +419,5 @@ typedef Types<int, double, MyPair<int, int> > TrimTypes;
INSTANTIATE_TYPED_TEST_SUITE_P(My, TrimmedTest, TrimTypes);
} // namespace library2
+
+GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127
diff --git a/googletest/test/gtest_dirs_test.cc b/googletest/test/gtest_dirs_test.cc
new file mode 100644
index 0000000..1a5b63d
--- /dev/null
+++ b/googletest/test/gtest_dirs_test.cc
@@ -0,0 +1,101 @@
+#include <sys/stat.h>
+
+#include <cstdlib>
+#include <cstring>
+#include <string>
+
+#include "gtest/gtest.h"
+#include "gtest/internal/gtest-port.h"
+
+#if GTEST_HAS_FILE_SYSTEM
+
+namespace {
+
+class SetEnv {
+ public:
+ // Sets the environment value with name `name` to `value`, unless `value` is
+ // nullptr, in which case it unsets it. Restores the original value on
+ // destruction.
+ SetEnv(const char* name, const char* value) : name_(name) {
+ const char* old_value = getenv(name);
+ if (old_value != nullptr) {
+ saved_value_ = old_value;
+ have_saved_value_ = true;
+ }
+ if (value == nullptr) {
+ GTEST_CHECK_POSIX_SUCCESS_(unsetenv(name));
+ } else {
+ GTEST_CHECK_POSIX_SUCCESS_(setenv(name, value, 1 /*overwrite*/));
+ }
+ }
+
+ ~SetEnv() {
+ if (have_saved_value_) {
+ GTEST_CHECK_POSIX_SUCCESS_(
+ setenv(name_.c_str(), saved_value_.c_str(), 1 /*overwrite*/));
+ } else {
+ GTEST_CHECK_POSIX_SUCCESS_(unsetenv(name_.c_str()));
+ }
+ }
+
+ private:
+ std::string name_;
+ bool have_saved_value_ = false;
+ std::string saved_value_;
+};
+
+class MakeTempDir {
+ public:
+ // Creates a directory with a unique name including `testname`.
+ // The destructor removes it.
+ explicit MakeTempDir(const std::string& testname) {
+ // mkdtemp requires that the last 6 characters of the input pattern
+ // are Xs, and the string is modified by replacing those characters.
+ std::string pattern = "/tmp/" + testname + "_XXXXXX";
+ GTEST_CHECK_(mkdtemp(pattern.data()) != nullptr);
+ dirname_ = pattern;
+ }
+
+ ~MakeTempDir() { GTEST_CHECK_POSIX_SUCCESS_(rmdir(dirname_.c_str())); }
+
+ const char* DirName() const { return dirname_.c_str(); }
+
+ private:
+ std::string dirname_;
+};
+
+bool StartsWith(const std::string& str, const std::string& prefix) {
+ return str.substr(0, prefix.size()) == prefix;
+}
+
+TEST(TempDirTest, InEnvironment) {
+ // Since the test infrastructure might be verifying directory existence or
+ // even creating subdirectories, we need to be careful that the directories we
+ // specify are actually valid.
+ MakeTempDir temp_dir("TempDirTest_InEnvironment");
+ SetEnv set_env("TEST_TMPDIR", temp_dir.DirName());
+ EXPECT_TRUE(StartsWith(testing::TempDir(), temp_dir.DirName()));
+}
+
+TEST(TempDirTest, NotInEnvironment) {
+ SetEnv set_env("TEST_TMPDIR", nullptr);
+ EXPECT_NE(testing::TempDir(), "");
+}
+
+TEST(SrcDirTest, InEnvironment) {
+ // Since the test infrastructure might be verifying directory existence or
+ // even creating subdirectories, we need to be careful that the directories we
+ // specify are actually valid.
+ MakeTempDir temp_dir("SrcDirTest_InEnvironment");
+ SetEnv set_env("TEST_SRCDIR", temp_dir.DirName());
+ EXPECT_TRUE(StartsWith(testing::SrcDir(), temp_dir.DirName()));
+}
+
+TEST(SrcDirTest, NotInEnvironment) {
+ SetEnv set_env("TEST_SRCDIR", nullptr);
+ EXPECT_NE(testing::SrcDir(), "");
+}
+
+#endif // GTEST_HAS_FILE_SYSTEM
+
+} // namespace
diff --git a/googletest/test/gtest_help_test.py b/googletest/test/gtest_help_test.py
index 642ab86..9261b87 100755
--- a/googletest/test/gtest_help_test.py
+++ b/googletest/test/gtest_help_test.py
@@ -43,6 +43,7 @@ import sys
from googletest.test import gtest_test_utils
+IS_DARWIN = os.name == 'posix' and os.uname()[0] == 'Darwin'
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
IS_GNUHURD = os.name == 'posix' and os.uname()[0] == 'GNU'
IS_GNUKFREEBSD = os.name == 'posix' and os.uname()[0] == 'GNU/kFreeBSD'
@@ -57,27 +58,43 @@ UNKNOWN_GTEST_PREFIXED_FLAG = FLAG_PREFIX + 'unknown_flag_for_testing'
LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests'
INTERNAL_FLAG_FOR_TESTING = FLAG_PREFIX + 'internal_flag_for_testing'
-SUPPORTS_DEATH_TESTS = "DeathTest" in gtest_test_utils.Subprocess(
- [PROGRAM_PATH, LIST_TESTS_FLAG]).output
+SUPPORTS_DEATH_TESTS = (
+ 'DeathTest'
+ in gtest_test_utils.Subprocess([PROGRAM_PATH, LIST_TESTS_FLAG]).output
+)
HAS_ABSL_FLAGS = '--has_absl_flags' in sys.argv
# The help message must match this regex.
HELP_REGEX = re.compile(
- FLAG_PREFIX + r'list_tests.*' +
- FLAG_PREFIX + r'filter=.*' +
- FLAG_PREFIX + r'also_run_disabled_tests.*' +
- FLAG_PREFIX + r'repeat=.*' +
- FLAG_PREFIX + r'shuffle.*' +
- FLAG_PREFIX + r'random_seed=.*' +
- FLAG_PREFIX + r'color=.*' +
- FLAG_PREFIX + r'brief.*' +
- FLAG_PREFIX + r'print_time.*' +
- FLAG_PREFIX + r'output=.*' +
- FLAG_PREFIX + r'break_on_failure.*' +
- FLAG_PREFIX + r'throw_on_failure.*' +
- FLAG_PREFIX + r'catch_exceptions=0.*',
- re.DOTALL)
+ FLAG_PREFIX
+ + r'list_tests.*'
+ + FLAG_PREFIX
+ + r'filter=.*'
+ + FLAG_PREFIX
+ + r'also_run_disabled_tests.*'
+ + FLAG_PREFIX
+ + r'repeat=.*'
+ + FLAG_PREFIX
+ + r'shuffle.*'
+ + FLAG_PREFIX
+ + r'random_seed=.*'
+ + FLAG_PREFIX
+ + r'color=.*'
+ + FLAG_PREFIX
+ + r'brief.*'
+ + FLAG_PREFIX
+ + r'print_time.*'
+ + FLAG_PREFIX
+ + r'output=.*'
+ + FLAG_PREFIX
+ + r'break_on_failure.*'
+ + FLAG_PREFIX
+ + r'throw_on_failure.*'
+ + FLAG_PREFIX
+ + r'catch_exceptions=0.*',
+ re.DOTALL,
+)
def RunWithFlag(flag):
@@ -120,7 +137,7 @@ class GTestHelpTest(gtest_test_utils.TestCase):
self.assertTrue(HELP_REGEX.search(output), output)
- if IS_LINUX or IS_GNUHURD or IS_GNUKFREEBSD or IS_OPENBSD:
+ if IS_DARWIN or IS_LINUX or IS_GNUHURD or IS_GNUKFREEBSD or IS_OPENBSD:
self.assertIn(STREAM_RESULT_TO_FLAG, output)
else:
self.assertNotIn(STREAM_RESULT_TO_FLAG, output)
@@ -171,14 +188,20 @@ class GTestHelpTest(gtest_test_utils.TestCase):
self.TestHelpFlag(UNKNOWN_GTEST_PREFIXED_FLAG)
def testRunsTestsWithoutHelpFlag(self):
- """Verifies that when no help flag is specified, the tests are run
- and the help message is not printed."""
+ """Verifies correct behavior when no help flag is specified.
+
+ Verifies that when no help flag is specified, the tests are run
+ and the help message is not printed.
+ """
self.TestNonHelpFlag(None)
def testRunsTestsWithGtestInternalFlag(self):
- """Verifies that the tests are run and no help message is printed when
- a flag starting with Google Test prefix and 'internal_' is supplied."""
+ """Verifies correct behavior when internal testing flag is specified.
+
+ Verifies that the tests are run and no help message is printed when
+ a flag starting with Google Test prefix and 'internal_' is supplied.
+ """
self.TestNonHelpFlag(INTERNAL_FLAG_FOR_TESTING)
diff --git a/googletest/test/gtest_help_test_.cc b/googletest/test/gtest_help_test_.cc
index da289f0..18b5f3c 100644
--- a/googletest/test/gtest_help_test_.cc
+++ b/googletest/test/gtest_help_test_.cc
@@ -39,6 +39,6 @@ TEST(HelpFlagTest, ShouldNotBeRun) {
ASSERT_TRUE(false) << "Tests shouldn't be run when --help is specified.";
}
-#if GTEST_HAS_DEATH_TEST
+#ifdef GTEST_HAS_DEATH_TEST
TEST(DeathTest, UsedByPythonScriptToDetectSupportForDeathTestsInThisBinary) {}
#endif
diff --git a/googletest/test/gtest_json_test_utils.py b/googletest/test/gtest_json_test_utils.py
index f62896c..86a5925 100644
--- a/googletest/test/gtest_json_test_utils.py
+++ b/googletest/test/gtest_json_test_utils.py
@@ -42,6 +42,7 @@ def normalize(obj):
Normalized output without any references to transient information that may
change from run to run.
"""
+
def _normalize(key, value):
if key == 'time':
return re.sub(r'^\d+(\.\d+)?s$', '*', value)
@@ -54,6 +55,7 @@ def normalize(obj):
return re.sub(r'^.*[/\\](.*)', '\\1', value)
else:
return normalize(value)
+
if isinstance(obj, dict):
return {k: _normalize(k, v) for k, v in obj.items()}
if isinstance(obj, list):
diff --git a/googletest/test/gtest_list_output_unittest.py b/googletest/test/gtest_list_output_unittest.py
index faacf10..afd521d 100644
--- a/googletest/test/gtest_list_output_unittest.py
+++ b/googletest/test/gtest_list_output_unittest.py
@@ -224,8 +224,7 @@ EXPECTED_JSON = """{
class GTestListTestsOutputUnitTest(gtest_test_utils.TestCase):
- """Unit test for Google Test's list tests with output to file functionality.
- """
+ """Unit test for Google Test's list tests with output to file functionality."""
def testXml(self):
"""Verifies XML output for listing tests in a Google Test binary.
@@ -244,19 +243,22 @@ class GTestListTestsOutputUnitTest(gtest_test_utils.TestCase):
self._TestOutput('json', EXPECTED_JSON)
def _GetOutput(self, out_format):
- file_path = os.path.join(gtest_test_utils.GetTempDir(),
- 'test_out.' + out_format)
+ file_path = os.path.join(
+ gtest_test_utils.GetTempDir(), 'test_out.' + out_format
+ )
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
- 'gtest_list_output_unittest_')
+ 'gtest_list_output_unittest_'
+ )
- command = ([
+ command = [
gtest_prog_path,
'%s=%s:%s' % (GTEST_OUTPUT_FLAG, out_format, file_path),
- '--gtest_list_tests'
- ])
+ '--gtest_list_tests',
+ ]
environ_copy = os.environ.copy()
p = gtest_test_utils.Subprocess(
- command, env=environ_copy, working_dir=gtest_test_utils.GetTempDir())
+ command, env=environ_copy, working_dir=gtest_test_utils.GetTempDir()
+ )
self.assertTrue(p.exited)
self.assertEqual(0, p.exit_code)
@@ -275,9 +277,10 @@ class GTestListTestsOutputUnitTest(gtest_test_utils.TestCase):
expected_line_re = re.compile(expected_line.strip())
self.assertTrue(
expected_line_re.match(actual_line.strip()),
- ('actual output of "%s",\n'
- 'which does not match expected regex of "%s"\n'
- 'on line %d' % (actual, expected_output, line_count)))
+ 'actual output of "%s",\n'
+ 'which does not match expected regex of "%s"\n'
+ 'on line %d' % (actual, expected_output, line_count),
+ )
line_count = line_count + 1
diff --git a/googletest/test/gtest_pred_impl_unittest.cc b/googletest/test/gtest_pred_impl_unittest.cc
index 3d43665..033e2d9 100644
--- a/googletest/test/gtest_pred_impl_unittest.cc
+++ b/googletest/test/gtest_pred_impl_unittest.cc
@@ -45,6 +45,7 @@
// stand-alone regression test.
#include <iostream>
+#include <ostream>
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
diff --git a/googletest/test/gtest_skip_check_output_test.py b/googletest/test/gtest_skip_check_output_test.py
index 1c87b44..b30a165 100755
--- a/googletest/test/gtest_skip_check_output_test.py
+++ b/googletest/test/gtest_skip_check_output_test.py
@@ -51,7 +51,8 @@ class SkipEntireEnvironmentTest(gtest_test_utils.TestCase):
skip_fixture = 'Skipped\nskipping all tests for this fixture\n'
self.assertIsNotNone(
re.search(skip_fixture + '.*' + skip_fixture, OUTPUT, flags=re.DOTALL),
- repr(OUTPUT))
+ repr(OUTPUT),
+ )
self.assertNotIn('FAILED', OUTPUT)
diff --git a/googletest/test/gtest_skip_environment_check_output_test.py b/googletest/test/gtest_skip_environment_check_output_test.py
index 6960b11..388a4e9 100755
--- a/googletest/test/gtest_skip_environment_check_output_test.py
+++ b/googletest/test/gtest_skip_environment_check_output_test.py
@@ -37,7 +37,8 @@ from googletest.test import gtest_test_utils
# Path to the gtest_skip_in_environment_setup_test binary
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
- 'gtest_skip_in_environment_setup_test')
+ 'gtest_skip_in_environment_setup_test'
+)
OUTPUT = gtest_test_utils.Subprocess([EXE_PATH]).output
diff --git a/googletest/test/gtest_stress_test.cc b/googletest/test/gtest_stress_test.cc
index 24b173f..0cf2185 100644
--- a/googletest/test/gtest_stress_test.cc
+++ b/googletest/test/gtest_stress_test.cc
@@ -30,12 +30,13 @@
// Tests that SCOPED_TRACE() and various Google Test assertions can be
// used in a large number of threads concurrently.
+#include <memory>
#include <vector>
#include "gtest/gtest.h"
#include "src/gtest-internal-inl.h"
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
namespace testing {
namespace {
@@ -118,8 +119,8 @@ TEST(StressTest, CanUseScopedTraceAndAssertionsInManyThreads) {
std::unique_ptr<ThreadWithParam<int> > threads[kThreadCount];
Notification threads_can_start;
for (int i = 0; i != kThreadCount; i++)
- threads[i].reset(
- new ThreadWithParam<int>(&ManyAsserts, i, &threads_can_start));
+ threads[i] = std::make_unique<ThreadWithParam<int>>(&ManyAsserts, i,
+ &threads_can_start);
threads_can_start.Notify();
diff --git a/googletest/test/gtest_test_utils.py b/googletest/test/gtest_test_utils.py
index eecc533..964fa9f 100755
--- a/googletest/test/gtest_test_utils.py
+++ b/googletest/test/gtest_test_utils.py
@@ -29,7 +29,7 @@
"""Unit test utilities for Google C++ Testing and Mocking Framework."""
# Suppresses the 'Import not at the top of the file' lint complaint.
-# pylint: disable-msg=C6204
+# pylint: disable=g-import-not-at-top
import os
import subprocess
@@ -43,7 +43,7 @@ import atexit
import shutil
import tempfile
import unittest as _test_module
-# pylint: enable-msg=C6204
+# pylint: enable=g-import-not-at-top
GTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT'
@@ -63,23 +63,22 @@ 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=C6409
+# environment.
+TestCase = _test_module.TestCase
# Initially maps a flag to its default value. After
# _ParseAndStripGTestFlags() is called, maps a flag to its actual value.
-_flag_map = {'source_dir': os.path.dirname(sys.argv[0]),
- 'build_dir': os.path.dirname(sys.argv[0])}
+_flag_map = {
+ 'source_dir': os.path.dirname(sys.argv[0]),
+ 'build_dir': os.path.dirname(sys.argv[0]),
+}
_gtest_flags_are_parsed = False
def _ParseAndStripGTestFlags(argv):
"""Parses and strips Google Test flags from argv. This is idempotent."""
- # 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=W0603
+ global _gtest_flags_are_parsed
if _gtest_flags_are_parsed:
return
@@ -94,7 +93,7 @@ def _ParseAndStripGTestFlags(argv):
while i < len(argv):
prefix = '--' + flag + '='
if argv[i].startswith(prefix):
- _flag_map[flag] = argv[i][len(prefix):]
+ _flag_map[flag] = argv[i][len(prefix) :]
del argv[i]
break
else:
@@ -150,15 +149,16 @@ def GetTestExecutablePath(executable_name, build_dir=None):
Args:
executable_name: name of the test binary that the test script runs.
- build_dir: directory where to look for executables, by default
- the result of GetBuildDir().
+ build_dir: directory where to look for executables, by default the
+ result of GetBuildDir().
Returns:
The absolute path of the test binary.
"""
- path = os.path.abspath(os.path.join(build_dir or GetBuildDir(),
- executable_name))
+ path = os.path.abspath(
+ os.path.join(build_dir or GetBuildDir(), executable_name)
+ )
if (IS_WINDOWS or IS_CYGWIN or IS_OS2) and not path.endswith('.exe'):
path += '.exe'
@@ -166,7 +166,8 @@ def GetTestExecutablePath(executable_name, build_dir=None):
message = (
'Unable to find the test binary "%s". Please make sure to provide\n'
'a path to the binary via the --build_dir flag or the BUILD_DIR\n'
- 'environment variable.' % path)
+ 'environment variable.' % path
+ )
print(message, file=sys.stderr)
sys.exit(1)
@@ -194,6 +195,7 @@ def GetExitStatus(exit_code):
class Subprocess:
+
def __init__(self, command, working_dir=None, capture_stderr=True, env=None):
"""Changes into a specified directory, if provided, and executes a command.
@@ -203,7 +205,7 @@ class Subprocess:
command: The command to run, in the form of sys.argv.
working_dir: The directory to change into.
capture_stderr: Determines whether to capture stderr in the output member
- or to discard it.
+ or to discard it.
env: Dictionary with environment to pass to the subprocess.
Returns:
@@ -223,9 +225,14 @@ class Subprocess:
else:
stderr = subprocess.PIPE
- p = subprocess.Popen(command,
- stdout=subprocess.PIPE, stderr=stderr,
- cwd=working_dir, universal_newlines=True, env=env)
+ p = subprocess.Popen(
+ command,
+ stdout=subprocess.PIPE,
+ stderr=stderr,
+ cwd=working_dir,
+ universal_newlines=True,
+ env=env,
+ )
# communicate returns a tuple with the file object for the child's
# output.
self.output = p.communicate()[0]
diff --git a/googletest/test/gtest_testbridge_test.py b/googletest/test/gtest_testbridge_test.py
index 1c2a303..0d58758 100755
--- a/googletest/test/gtest_testbridge_test.py
+++ b/googletest/test/gtest_testbridge_test.py
@@ -52,7 +52,7 @@ class GTestTestFilterTest(gtest_test_utils.TestCase):
subprocess_env[TESTBRIDGE_NAME] = '*.TestThatSucceeds'
p = gtest_test_utils.Subprocess(COMMAND, env=subprocess_env)
- self.assertEquals(0, p.exit_code)
+ self.assertEqual(0, p.exit_code)
Assert('filter = *.TestThatSucceeds' in p.output)
Assert('[ OK ] TestFilterTest.TestThatSucceeds' in p.output)
diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc
index 329ca54..bd4fc60 100644
--- a/googletest/test/gtest_unittest.cc
+++ b/googletest/test/gtest_unittest.cc
@@ -60,7 +60,9 @@ TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
#include <cstdint>
#include <map>
+#include <memory>
#include <ostream>
+#include <set>
#include <string>
#include <type_traits>
#include <unordered_set>
@@ -209,7 +211,6 @@ using testing::TestPartResult;
using testing::TestPartResultArray;
using testing::TestProperty;
using testing::TestResult;
-using testing::TestSuite;
using testing::TimeInMillis;
using testing::UnitTest;
using testing::internal::AlwaysFalse;
@@ -225,7 +226,6 @@ using testing::internal::FloatingPoint;
using testing::internal::ForEach;
using testing::internal::FormatEpochTimeInMillisAsIso8601;
using testing::internal::FormatTimeInMillisAsSeconds;
-using testing::internal::GetCurrentOsStackTraceExceptTop;
using testing::internal::GetElementOr;
using testing::internal::GetNextRandomSeed;
using testing::internal::GetRandomSeedFromFlag;
@@ -242,8 +242,6 @@ using testing::internal::IsNotContainer;
using testing::internal::kMaxRandomSeed;
using testing::internal::kTestTypeIdInGoogleTest;
using testing::internal::NativeArray;
-using testing::internal::OsStackTraceGetter;
-using testing::internal::OsStackTraceGetterInterface;
using testing::internal::ParseFlag;
using testing::internal::RelationToSourceCopy;
using testing::internal::RelationToSourceReference;
@@ -257,7 +255,6 @@ using testing::internal::StreamableToString;
using testing::internal::String;
using testing::internal::TestEventListenersAccessor;
using testing::internal::TestResultAccessor;
-using testing::internal::UnitTestImpl;
using testing::internal::WideStringToUtf8;
using testing::internal::edit_distance::CalculateOptimalEdits;
using testing::internal::edit_distance::CreateUnifiedDiff;
@@ -268,7 +265,7 @@ using testing::internal::CaptureStdout;
using testing::internal::GetCapturedStdout;
#endif
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
using testing::internal::ThreadWithParam;
#endif
@@ -381,7 +378,7 @@ TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) {
// Tests FormatTimeInMillisAsSeconds().
TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
- EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
+ EXPECT_EQ("0.", FormatTimeInMillisAsSeconds(0));
}
TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
@@ -389,7 +386,11 @@ TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
- EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
+ EXPECT_EQ("3.", FormatTimeInMillisAsSeconds(3000));
+ EXPECT_EQ("10.", FormatTimeInMillisAsSeconds(10000));
+ EXPECT_EQ("100.", FormatTimeInMillisAsSeconds(100000));
+ EXPECT_EQ("123.456", FormatTimeInMillisAsSeconds(123456));
+ EXPECT_EQ("1234567.89", FormatTimeInMillisAsSeconds(1234567890));
}
TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
@@ -397,7 +398,11 @@ TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
- EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
+ EXPECT_EQ("-3.", FormatTimeInMillisAsSeconds(-3000));
+ EXPECT_EQ("-10.", FormatTimeInMillisAsSeconds(-10000));
+ EXPECT_EQ("-100.", FormatTimeInMillisAsSeconds(-100000));
+ EXPECT_EQ("-123.456", FormatTimeInMillisAsSeconds(-123456));
+ EXPECT_EQ("-1234567.89", FormatTimeInMillisAsSeconds(-1234567890));
}
// Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
@@ -415,10 +420,12 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
private:
void SetUp() override {
- saved_tz_ = nullptr;
+ saved_tz_.reset();
- GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */)
- if (getenv("TZ")) saved_tz_ = strdup(getenv("TZ"));
+ GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv: deprecated */)
+ if (const char* tz = getenv("TZ")) {
+ saved_tz_ = std::make_unique<std::string>(tz);
+ }
GTEST_DISABLE_MSC_DEPRECATED_POP_()
// Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
@@ -428,16 +435,15 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
}
void TearDown() override {
- SetTimeZone(saved_tz_);
- free(const_cast<char*>(saved_tz_));
- saved_tz_ = nullptr;
+ SetTimeZone(saved_tz_ != nullptr ? saved_tz_->c_str() : nullptr);
+ saved_tz_.reset();
}
static void SetTimeZone(const char* time_zone) {
// tzset() distinguishes between the TZ variable being present and empty
// and not being present, so we have to consider the case of time_zone
// being NULL.
-#if _MSC_VER || GTEST_OS_WINDOWS_MINGW
+#if defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW)
// ...Unless it's MSVC, whose standard library's _putenv doesn't
// distinguish between an empty and a missing variable.
const std::string env_var =
@@ -447,7 +453,7 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
tzset();
GTEST_DISABLE_MSC_WARNINGS_POP_()
#else
-#if GTEST_OS_LINUX_ANDROID && __ANDROID_API__ < 21
+#if defined(GTEST_OS_LINUX_ANDROID) && __ANDROID_API__ < 21
// Work around KitKat bug in tzset by setting "UTC" before setting "UTC+00".
// See https://github.com/android/ndk/issues/1604.
setenv("TZ", "UTC", 1);
@@ -462,7 +468,7 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
#endif
}
- const char* saved_tz_;
+ std::unique_ptr<std::string> saved_tz_; // Empty and null are different here
};
const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
@@ -1079,7 +1085,7 @@ TEST(StringTest, CaseInsensitiveWideCStringEquals) {
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
}
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Tests String::ShowWideCString().
TEST(StringTest, ShowWideCString) {
@@ -1088,7 +1094,7 @@ TEST(StringTest, ShowWideCString) {
EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
}
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
TEST(StringTest, AnsiAndUtf16Null) {
EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
@@ -1178,7 +1184,7 @@ TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
EXPECT_EQ(1, results.size());
}
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
class ScopedFakeTestPartResultReporterWithThreadsTest
: public ScopedFakeTestPartResultReporterTest {
@@ -1336,7 +1342,7 @@ TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
"");
}
-#if GTEST_IS_THREADSAFE
+#ifdef GTEST_IS_THREADSAFE
typedef ScopedFakeTestPartResultReporterWithThreadsTest
ExpectFailureWithThreadsTest;
@@ -1665,7 +1671,7 @@ TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); }
// value. If the value argument is "", unsets the environment
// variable. The caller must ensure that both arguments are not NULL.
static void SetEnv(const char* name, const char* value) {
-#if GTEST_OS_WINDOWS_MOBILE
+#ifdef GTEST_OS_WINDOWS_MOBILE
// Environment variables are not supported on Windows CE.
return;
#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
@@ -1688,7 +1694,7 @@ static void SetEnv(const char* name, const char* value) {
// We cast away the 'const' since that would work for both variants.
putenv(const_cast<char*>(added_env[name]->c_str()));
delete prev_env;
-#elif GTEST_OS_WINDOWS // If we are on Windows proper.
+#elif defined(GTEST_OS_WINDOWS) // If we are on Windows proper.
_putenv((Message() << name << "=" << value).GetString().c_str());
#else
if (*value == '\0') {
@@ -1699,7 +1705,7 @@ static void SetEnv(const char* name, const char* value) {
#endif // GTEST_OS_WINDOWS_MOBILE
}
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
// Environment variables are not supported on Windows CE.
using testing::internal::Int32FromGTestEnv;
@@ -1808,7 +1814,7 @@ TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
// Tests that Int32FromEnvOrDie() parses the value of the var or
// returns the correct default.
// Environment variables are not supported on Windows CE.
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
@@ -1881,7 +1887,7 @@ TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
// Tests that sharding is enabled if total_shards > 1 and
// we are not in a death test subprocess.
// Environment variables are not supported on Windows CE.
-#if !GTEST_OS_WINDOWS_MOBILE
+#ifndef GTEST_OS_WINDOWS_MOBILE
TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
SetEnv(index_var_, "4");
SetEnv(total_var_, "22");
@@ -3915,7 +3921,7 @@ TEST(AssertionTest, NamedEnum) {
enum {
kCaseA = -1,
-#if GTEST_OS_LINUX
+#ifdef GTEST_OS_LINUX
// We want to test the case where the size of the anonymous enum is
// larger than sizeof(int), to make sure our implementation of the
@@ -3938,7 +3944,7 @@ enum {
};
TEST(AssertionTest, AnonymousEnum) {
-#if GTEST_OS_LINUX
+#ifdef GTEST_OS_LINUX
EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
@@ -3972,7 +3978,7 @@ TEST(AssertionTest, AnonymousEnum) {
#endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
static HRESULT UnexpectedHRESULTFailure() { return E_UNEXPECTED; }
@@ -4332,7 +4338,7 @@ TEST(AssertionWithMessageTest, ASSERT_TRUE) {
"(null)(null)");
}
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Tests using wide strings in assertion messages.
TEST(AssertionWithMessageTest, WideStringMessage) {
EXPECT_NONFATAL_FAILURE(
@@ -6167,12 +6173,12 @@ TEST_F(ParseFlagsTest, FilterBad) {
const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
-#if GTEST_HAS_ABSL && GTEST_HAS_DEATH_TEST
+#if defined(GTEST_HAS_ABSL) && defined(GTEST_HAS_DEATH_TEST)
// Invalid flag arguments are a fatal error when using the Abseil Flags.
EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true),
testing::ExitedWithCode(1),
"ERROR: Missing the value for the flag 'gtest_filter'");
-#elif !GTEST_HAS_ABSL
+#elif !defined(GTEST_HAS_ABSL)
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
#else
static_cast<void>(argv);
@@ -6186,12 +6192,12 @@ TEST_F(ParseFlagsTest, OutputEmpty) {
const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
-#if GTEST_HAS_ABSL && GTEST_HAS_DEATH_TEST
+#if defined(GTEST_HAS_ABSL) && defined(GTEST_HAS_DEATH_TEST)
// Invalid flag arguments are a fatal error when using the Abseil Flags.
EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true),
testing::ExitedWithCode(1),
"ERROR: Missing the value for the flag 'gtest_output'");
-#elif !GTEST_HAS_ABSL
+#elif !defined(GTEST_HAS_ABSL)
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
#else
static_cast<void>(argv);
@@ -6199,7 +6205,7 @@ TEST_F(ParseFlagsTest, OutputEmpty) {
#endif
}
-#if GTEST_HAS_ABSL
+#ifdef GTEST_HAS_ABSL
TEST_F(ParseFlagsTest, AbseilPositionalFlags) {
const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", "--",
"--other_flag", nullptr};
@@ -6213,7 +6219,7 @@ TEST_F(ParseFlagsTest, AbseilPositionalFlags) {
}
#endif
-#if GTEST_OS_WINDOWS
+#ifdef GTEST_OS_WINDOWS
// Tests parsing wide strings.
TEST_F(ParseFlagsTest, WideStrings) {
const wchar_t* argv[] = {L"foo.exe",
@@ -6603,7 +6609,7 @@ TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
GTEST_FLAG_SET(color, "auto");
-#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
+#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW)
// On Windows, we ignore the TERM variable as it's usually not set.
SetEnv("TERM", "dumb");
@@ -6636,6 +6642,9 @@ TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
SetEnv("TERM", "xterm-color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
+ SetEnv("TERM", "xterm-kitty"); // TERM supports colors.
+ EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
+
SetEnv("TERM", "xterm-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
@@ -6966,7 +6975,7 @@ TEST(EventListenerTest, SuppressEventForwarding) {
// Tests that events generated by Google Test are not forwarded in
// death test subprocesses.
-TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
+TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprocesses) {
EXPECT_DEATH_IF_SUPPORTED(
{
GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
diff --git a/googletest/test/gtest_xml_outfile2_test_.cc b/googletest/test/gtest_xml_outfile2_test_.cc
index f9a2a6e..ed58dc8 100644
--- a/googletest/test/gtest_xml_outfile2_test_.cc
+++ b/googletest/test/gtest_xml_outfile2_test_.cc
@@ -38,6 +38,38 @@ class PropertyTwo : public testing::Test {
void TearDown() override { RecordProperty("TearDownProp", 2); }
};
-TEST_F(PropertyTwo, TestSomeProperties) {
- RecordProperty("TestSomeProperty", 2);
+TEST_F(PropertyTwo, TestInt64ConvertibleProperties) {
+ float float_prop = 3.25;
+ RecordProperty("TestFloatProperty", float_prop);
+
+ double double_prop = 4.75;
+ RecordProperty("TestDoubleProperty", double_prop);
+
+ // Validate we can write an unsigned size_t as a property
+ size_t size_t_prop = 5;
+ RecordProperty("TestSizetProperty", size_t_prop);
+
+ bool bool_prop = true;
+ RecordProperty("TestBoolProperty", bool_prop);
+
+ char char_prop = 'A';
+ RecordProperty("TestCharProperty", char_prop);
+
+ int16_t int16_prop = 6;
+ RecordProperty("TestInt16Property", int16_prop);
+
+ int32_t int32_prop = 7;
+ RecordProperty("TestInt32Property", int32_prop);
+
+ int64_t int64_prop = 8;
+ RecordProperty("TestInt64Property", int64_prop);
+
+ enum Foo {
+ NINE = 9,
+ };
+ Foo enum_prop = NINE;
+ RecordProperty("TestEnumProperty", enum_prop);
+
+ std::atomic<int> atomic_int_prop(10);
+ RecordProperty("TestAtomicIntProperty", atomic_int_prop);
}
diff --git a/googletest/test/gtest_xml_outfiles_test.py b/googletest/test/gtest_xml_outfiles_test.py
index c129e64..50291b0 100755
--- a/googletest/test/gtest_xml_outfiles_test.py
+++ b/googletest/test/gtest_xml_outfiles_test.py
@@ -57,10 +57,19 @@ EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?>
EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests">
<testsuite name="PropertyTwo" tests="1" failures="0" skipped="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="TestSomeProperties" file="gtest_xml_outfile2_test_.cc" line="41" status="run" result="completed" time="*" timestamp="*" classname="PropertyTwo">
+ <testcase name="TestInt64ConvertibleProperties" file="gtest_xml_outfile2_test_.cc" line="41" status="run" result="completed" time="*" timestamp="*" classname="PropertyTwo">
<properties>
<property name="SetUpProp" value="2"/>
- <property name="TestSomeProperty" value="2"/>
+ <property name="TestFloatProperty" value="3.25"/>
+ <property name="TestDoubleProperty" value="4.75"/>
+ <property name="TestSizetProperty" value="5"/>
+ <property name="TestBoolProperty" value="true"/>
+ <property name="TestCharProperty" value="A"/>
+ <property name="TestInt16Property" value="6"/>
+ <property name="TestInt32Property" value="7"/>
+ <property name="TestInt64Property" value="8"/>
+ <property name="TestEnumProperty" value="9"/>
+ <property name="TestAtomicIntProperty" value="10"/>
<property name="TearDownProp" value="2"/>
</properties>
</testcase>
@@ -76,8 +85,9 @@ class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase):
# 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.output_dir_ = os.path.join(
+ gtest_test_utils.GetTempDir(), GTEST_OUTPUT_SUBDIR, ""
+ )
self.DeleteFilesAndDir()
def tearDown(self):
@@ -106,17 +116,20 @@ class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase):
def _TestOutFile(self, test_name, expected_xml):
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name)
command = [gtest_prog_path, "--gtest_output=xml:%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)
+ p = gtest_test_utils.Subprocess(
+ command, working_dir=gtest_test_utils.GetTempDir()
+ )
+ self.assertTrue(p.exited)
+ self.assertEqual(0, p.exit_code)
output_file_name1 = test_name + ".xml"
output_file1 = os.path.join(self.output_dir_, output_file_name1)
- output_file_name2 = 'lt-' + 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)
+ self.assertTrue(
+ os.path.isfile(output_file1) or os.path.isfile(output_file2),
+ output_file1,
+ )
expected = minidom.parseString(expected_xml)
if os.path.isfile(output_file1):
@@ -124,8 +137,7 @@ class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase):
else:
actual = minidom.parse(output_file2)
self.NormalizeXml(actual.documentElement)
- self.AssertEquivalentNodes(expected.documentElement,
- actual.documentElement)
+ self.AssertEquivalentNodes(expected.documentElement, actual.documentElement)
expected.unlink()
actual.unlink()
diff --git a/googletest/test/gtest_xml_output_unittest.py b/googletest/test/gtest_xml_output_unittest.py
index e1b7f1f..e7e44fc 100755
--- a/googletest/test/gtest_xml_output_unittest.py
+++ b/googletest/test/gtest_xml_output_unittest.py
@@ -59,8 +59,10 @@ SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv
if SUPPORTS_STACK_TRACES:
STACK_TRACE_TEMPLATE = '\nStack trace:\n*'
+ STACK_TRACE_ENTITY_TEMPLATE = ''
else:
- STACK_TRACE_TEMPLATE = ''
+ STACK_TRACE_TEMPLATE = '\n'
+ STACK_TRACE_ENTITY_TEMPLATE = '&#x0A;'
# unittest.main() can't handle unknown flags
sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG)
@@ -71,7 +73,7 @@ EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
</testsuite>
<testsuite name="FailedTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="Fails" file="gtest_xml_output_unittest_.cc" line="59" status="run" result="completed" time="*" timestamp="*" classname="FailedTest">
- <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
+ <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2%(stack_entity)s" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Expected equality of these values:
1
2%(stack)s]]></failure>
@@ -80,11 +82,11 @@ Expected equality of these values:
<testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="86" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"/>
<testcase name="Fails" file="gtest_xml_output_unittest_.cc" line="91" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest">
- <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
+ <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2%(stack_entity)s" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Expected equality of these values:
1
2%(stack)s]]></failure>
- <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 2&#x0A; 3" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
+ <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 2&#x0A; 3%(stack_entity)s" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Expected equality of these values:
2
3%(stack)s]]></failure>
@@ -93,14 +95,14 @@ Expected equality of these values:
</testsuite>
<testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="OutputsCData" file="gtest_xml_output_unittest_.cc" line="100" status="run" result="completed" time="*" timestamp="*" classname="XmlQuotingTest">
- <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;XML output: &lt;?xml encoding=&quot;utf-8&quot;&gt;&lt;top&gt;&lt;![CDATA[cdata text]]&gt;&lt;/top&gt;" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
+ <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;XML output: &lt;?xml encoding=&quot;utf-8&quot;&gt;&lt;top&gt;&lt;![CDATA[cdata text]]&gt;&lt;/top&gt;%(stack_entity)s" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]&gt;<![CDATA[</top>%(stack)s]]></failure>
</testcase>
</testsuite>
<testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="InvalidCharactersInMessage" file="gtest_xml_output_unittest_.cc" line="107" status="run" result="completed" time="*" timestamp="*" classname="InvalidCharactersTest">
- <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
+ <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;Invalid characters in brackets []%(stack_entity)s" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Failed
Invalid characters in brackets []%(stack)s]]></failure>
</testcase>
@@ -110,19 +112,19 @@ Invalid characters in brackets []%(stack)s]]></failure>
</testsuite>
<testsuite name="SkippedTest" tests="3" failures="1" disabled="0" skipped="2" errors="0" time="*" timestamp="*">
<testcase name="Skipped" status="run" file="gtest_xml_output_unittest_.cc" line="73" result="skipped" time="*" timestamp="*" classname="SkippedTest">
- <skipped message="gtest_xml_output_unittest_.cc:*&#x0A;"><![CDATA[gtest_xml_output_unittest_.cc:*
+ <skipped message="gtest_xml_output_unittest_.cc:*&#x0A;%(stack_entity)s"><![CDATA[gtest_xml_output_unittest_.cc:*
%(stack)s]]></skipped>
</testcase>
<testcase name="SkippedWithMessage" file="gtest_xml_output_unittest_.cc" line="77" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest">
- <skipped message="gtest_xml_output_unittest_.cc:*&#x0A;It is good practice to tell why you skip a test."><![CDATA[gtest_xml_output_unittest_.cc:*
+ <skipped message="gtest_xml_output_unittest_.cc:*&#x0A;It is good practice to tell why you skip a test.%(stack_entity)s"><![CDATA[gtest_xml_output_unittest_.cc:*
It is good practice to tell why you skip a test.%(stack)s]]></skipped>
</testcase>
<testcase name="SkippedAfterFailure" file="gtest_xml_output_unittest_.cc" line="81" status="run" result="completed" time="*" timestamp="*" classname="SkippedTest">
- <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
+ <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2%(stack_entity)s" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Expected equality of these values:
1
2%(stack)s]]></failure>
- <skipped message="gtest_xml_output_unittest_.cc:*&#x0A;It is good practice to tell why you skip a test."><![CDATA[gtest_xml_output_unittest_.cc:*
+ <skipped message="gtest_xml_output_unittest_.cc:*&#x0A;It is good practice to tell why you skip a test.%(stack_entity)s"><![CDATA[gtest_xml_output_unittest_.cc:*
It is good practice to tell why you skip a test.%(stack)s]]></skipped>
</testcase>
@@ -187,7 +189,8 @@ It is good practice to tell why you skip a test.%(stack)s]]></skipped>
<testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="178" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/1" />
</testsuite>
</testsuites>""" % {
- 'stack': STACK_TRACE_TEMPLATE
+ 'stack': STACK_TRACE_TEMPLATE,
+ 'stack_entity': STACK_TRACE_ENTITY_TEMPLATE,
}
EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
@@ -221,32 +224,37 @@ EXPECTED_NO_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
timestamp="*" name="AllTests">
<testsuite name="NonTestSuiteFailure" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="" status="run" result="completed" time="*" timestamp="*" classname="">
- <failure message="gtest_no_test_unittest.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2" type=""><![CDATA[gtest_no_test_unittest.cc:*
+ <failure message="gtest_no_test_unittest.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2%(stack_entity)s" type=""><![CDATA[gtest_no_test_unittest.cc:*
Expected equality of these values:
1
2%(stack)s]]></failure>
</testcase>
</testsuite>
</testsuites>""" % {
- 'stack': STACK_TRACE_TEMPLATE
+ 'stack': STACK_TRACE_TEMPLATE,
+ 'stack_entity': STACK_TRACE_ENTITY_TEMPLATE,
}
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
+SUPPORTS_TYPED_TESTS = (
+ 'TypedTest'
+ in gtest_test_utils.Subprocess(
+ [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False
+ ).output
+)
class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
- """
- Unit test for Google Test's XML output functionality.
- """
+ """Unit test for Google Test's XML 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 testNonEmptyXmlOutput(self):
- """
+ """Generates non-empty XML and verifies it matches the expected output.
+
Runs a test program that generates a non-empty XML output, and
tests that the XML output is expected.
"""
@@ -273,28 +281,34 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
# 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,
- 'XML datettime string %s has incorrect format' % date_time_str)
+ re.match, 'XML datettime string %s has incorrect format' % date_time_str
+ )
date_time_from_xml = 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)))
+ 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_xml)
# timestamp value should be near the current local time
- self.assertTrue(time_delta < datetime.timedelta(seconds=600),
- 'time_delta is %s' % time_delta)
+ self.assertLess(time_delta, datetime.timedelta(seconds=600))
actual.unlink()
def testDefaultOutputFile(self):
- """
+ """Tests XML file with default name is created when name is not specified.
+
Confirms that Google Test produces an XML 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)
+ output_file = os.path.join(
+ gtest_test_utils.GetTempDir(), GTEST_DEFAULT_OUTPUT_FILE
+ )
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
- 'gtest_no_test_unittest')
+ 'gtest_no_test_unittest'
+ )
try:
os.remove(output_file)
except OSError:
@@ -304,39 +318,47 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
p = gtest_test_utils.Subprocess(
[gtest_prog_path, '%s=xml' % 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))
+ working_dir=gtest_test_utils.GetTempDir(),
+ )
+ self.assertTrue(p.exited)
+ self.assertEqual(0, p.exit_code)
+ self.assertTrue(os.path.isfile(output_file))
def testSuppressedXmlOutput(self):
- """
+ """Verifies XML output is suppressed if default listener is shut down.
+
Tests that no XML file is generated if the default XML listener is
shut down before RUN_ALL_TESTS is invoked.
"""
- xml_path = os.path.join(gtest_test_utils.GetTempDir(),
- GTEST_PROGRAM_NAME + 'out.xml')
+ xml_path = os.path.join(
+ gtest_test_utils.GetTempDir(), GTEST_PROGRAM_NAME + 'out.xml'
+ )
if os.path.isfile(xml_path):
os.remove(xml_path)
- command = [GTEST_PROGRAM_PATH,
- '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path),
- '--shut_down_xml']
+ command = [
+ GTEST_PROGRAM_PATH,
+ '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_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))
+ '%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.assertTrue(p.exited)
+ self.assertEqual(
+ 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(xml_path))
+ self.assertFalse(os.path.isfile(xml_path))
def testFilteredTestXmlOutput(self):
"""Verifies XML output when a filter is applied.
@@ -345,8 +367,12 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
non-selected tests do not show up in the XML output.
"""
- self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED_TEST_XML, 0,
- extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG])
+ self._TestXmlOutput(
+ GTEST_PROGRAM_NAME,
+ EXPECTED_FILTERED_TEST_XML,
+ 0,
+ extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG],
+ )
def testShardedTestXmlOutput(self):
"""Verifies XML output when run using multiple shards.
@@ -359,53 +385,81 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
GTEST_PROGRAM_NAME,
EXPECTED_SHARDED_TEST_XML,
0,
- extra_env={SHARD_INDEX_ENV_VAR: '0',
- TOTAL_SHARDS_ENV_VAR: '10'})
+ extra_env={SHARD_INDEX_ENV_VAR: '0', TOTAL_SHARDS_ENV_VAR: '10'},
+ )
+
+ def _GetXmlOutput(
+ self, gtest_prog_name, extra_args, extra_env, expected_exit_code
+ ):
+ """Returns the XML output generated by running the program gtest_prog_name.
- def _GetXmlOutput(self, gtest_prog_name, extra_args, extra_env,
- expected_exit_code):
- """
- Returns the xml output generated by running the program gtest_prog_name.
Furthermore, the program's exit code must be expected_exit_code.
+
+ Args:
+ gtest_prog_name: Program to run.
+ extra_args: Optional arguments to pass to program.
+ extra_env: Optional environment variables to set.
+ expected_exit_code: Expected exit code from running gtest_prog_name.
"""
- xml_path = os.path.join(gtest_test_utils.GetTempDir(),
- gtest_prog_name + 'out.xml')
+ xml_path = os.path.join(
+ gtest_test_utils.GetTempDir(), gtest_prog_name + 'out.xml'
+ )
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)
- command = ([gtest_prog_path, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path)] +
- extra_args)
+ command = [
+ gtest_prog_path,
+ '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path),
+ ] + extra_args
environ_copy = os.environ.copy()
if extra_env:
environ_copy.update(extra_env)
p = gtest_test_utils.Subprocess(command, env=environ_copy)
if p.terminated_by_signal:
- self.assert_(False,
- '%s was killed by signal %d' % (gtest_prog_name, p.signal))
+ self.assertTrue(
+ 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))
+ self.assertTrue(p.exited)
+ self.assertEqual(
+ 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),
+ )
actual = minidom.parse(xml_path)
return actual
- def _TestXmlOutput(self, gtest_prog_name, expected_xml,
- expected_exit_code, extra_args=None, extra_env=None):
- """
+ def _TestXmlOutput(
+ self,
+ gtest_prog_name,
+ expected_xml,
+ expected_exit_code,
+ extra_args=None,
+ extra_env=None,
+ ):
+ """Asserts that the XML document matches.
+
Asserts that the XML document generated by running the program
gtest_prog_name matches expected_xml, a string containing another
XML document. Furthermore, the program's exit code must be
expected_exit_code.
+
+ Args:
+ gtest_prog_name: Program to run.
+ expected_xml: Path to XML document to match.
+ expected_exit_code: Expected exit code from running gtest_prog_name.
+ extra_args: Optional arguments to pass to program.
+ extra_env: Optional environment variables to set.
"""
- actual = self._GetXmlOutput(gtest_prog_name, extra_args or [],
- extra_env or {}, expected_exit_code)
+ actual = self._GetXmlOutput(
+ gtest_prog_name, extra_args or [], extra_env or {}, expected_exit_code
+ )
expected = minidom.parseString(expected_xml)
self.NormalizeXml(actual.documentElement)
- self.AssertEquivalentNodes(expected.documentElement,
- actual.documentElement)
+ self.AssertEquivalentNodes(expected.documentElement, actual.documentElement)
expected.unlink()
actual.unlink()
diff --git a/googletest/test/gtest_xml_test_utils.py b/googletest/test/gtest_xml_test_utils.py
index c6fb9f4..8fcb693 100755
--- a/googletest/test/gtest_xml_test_utils.py
+++ b/googletest/test/gtest_xml_test_utils.py
@@ -35,14 +35,13 @@ from googletest.test import gtest_test_utils
GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml'
-class GTestXMLTestCase(gtest_test_utils.TestCase):
- """
- Base class for tests of Google Test's XML output functionality.
- """
+class GTestXMLTestCase(gtest_test_utils.TestCase):
+ """Base class for tests of Google Test's XML output functionality."""
def AssertEquivalentNodes(self, expected_node, actual_node):
- """
+ """Asserts that actual_node is equivalent to expected_node.
+
Asserts that actual_node (a DOM node object) is equivalent to
expected_node (another DOM node object), in that either both of
them are CDATA nodes and have the same value, or both are DOM
@@ -58,46 +57,66 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
CDATA sections) as expected_node. Note that we ignore the
order of the children as they are not guaranteed to be in any
particular order.
+
+ Args:
+ expected_node: expected DOM node object
+ actual_node: actual DOM node object
"""
if expected_node.nodeType == Node.CDATA_SECTION_NODE:
- self.assertEquals(Node.CDATA_SECTION_NODE, actual_node.nodeType)
- self.assertEquals(expected_node.nodeValue, actual_node.nodeValue)
+ self.assertEqual(Node.CDATA_SECTION_NODE, actual_node.nodeType)
+ self.assertEqual(expected_node.nodeValue, actual_node.nodeValue)
return
- self.assertEquals(Node.ELEMENT_NODE, actual_node.nodeType)
- self.assertEquals(Node.ELEMENT_NODE, expected_node.nodeType)
- self.assertEquals(expected_node.tagName, actual_node.tagName)
+ self.assertEqual(Node.ELEMENT_NODE, actual_node.nodeType)
+ self.assertEqual(Node.ELEMENT_NODE, expected_node.nodeType)
+ self.assertEqual(expected_node.tagName, actual_node.tagName)
expected_attributes = expected_node.attributes
actual_attributes = actual_node.attributes
- self.assertEquals(
- expected_attributes.length, actual_attributes.length,
- 'attribute numbers differ in element %s:\nExpected: %r\nActual: %r' % (
- actual_node.tagName, expected_attributes.keys(),
- actual_attributes.keys()))
+ self.assertEqual(
+ expected_attributes.length,
+ actual_attributes.length,
+ 'attribute numbers differ in element %s:\nExpected: %r\nActual: %r'
+ % (
+ actual_node.tagName,
+ expected_attributes.keys(),
+ actual_attributes.keys(),
+ ),
+ )
for i in range(expected_attributes.length):
expected_attr = expected_attributes.item(i)
actual_attr = actual_attributes.get(expected_attr.name)
- self.assert_(
+ self.assertTrue(
actual_attr is not None,
- 'expected attribute %s not found in element %s' %
- (expected_attr.name, actual_node.tagName))
- self.assertEquals(
- expected_attr.value, actual_attr.value,
- ' values of attribute %s in element %s differ: %s vs %s' %
- (expected_attr.name, actual_node.tagName,
- expected_attr.value, actual_attr.value))
+ 'expected attribute %s not found in element %s'
+ % (expected_attr.name, actual_node.tagName),
+ )
+ self.assertEqual(
+ expected_attr.value,
+ actual_attr.value,
+ ' values of attribute %s in element %s differ: %s vs %s'
+ % (
+ expected_attr.name,
+ actual_node.tagName,
+ expected_attr.value,
+ actual_attr.value,
+ ),
+ )
expected_children = self._GetChildren(expected_node)
actual_children = self._GetChildren(actual_node)
- self.assertEquals(
- len(expected_children), len(actual_children),
- 'number of child elements differ in element ' + actual_node.tagName)
+ self.assertEqual(
+ len(expected_children),
+ len(actual_children),
+ 'number of child elements differ in element ' + actual_node.tagName,
+ )
for child_id, child in expected_children.items():
- self.assert_(child_id in actual_children,
- '<%s> is not in <%s> (in element %s)' %
- (child_id, actual_children, actual_node.tagName))
+ self.assertTrue(
+ child_id in actual_children,
+ '<%s> is not in <%s> (in element %s)'
+ % (child_id, actual_children, actual_node.tagName),
+ )
self.AssertEquivalentNodes(child, actual_children[child_id])
identifying_attribute = {
@@ -110,40 +129,54 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
}
def _GetChildren(self, element):
- """
- Fetches all of the child nodes of element, a DOM Element object.
- Returns them as the values of a dictionary keyed by the IDs of the
- children. For <testsuites>, <testsuite>, <testcase>, and <property>
- elements, the ID is the value of their "name" attribute; for <failure>
- elements, it is the value of the "message" attribute; for <properties>
- elements, it is the value of their parent's "name" attribute plus the
- literal string "properties"; CDATA sections and non-whitespace
- text nodes are concatenated into a single CDATA section with ID
- "detail". An exception is raised if any element other than the above
- four is encountered, if two child elements with the same identifying
- attributes are encountered, or if any other type of node is encountered.
+ """Fetches all of the child nodes of element, a DOM Element object.
+
+ Returns them as the values of a dictionary keyed by the IDs of the children.
+ For <testsuites>, <testsuite>, <testcase>, and <property> elements, the ID
+ is the value of their "name" attribute; for <failure> elements, it is the
+ value of the "message" attribute; for <properties> elements, it is the value
+ of their parent's "name" attribute plus the literal string "properties";
+ CDATA sections and non-whitespace text nodes are concatenated into a single
+ CDATA section with ID "detail". An exception is raised if any element other
+ than the above four is encountered, if two child elements with the same
+ identifying attributes are encountered, or if any other type of node is
+ encountered.
+
+ Args:
+ element: DOM Element object
+
+ Returns:
+ Dictionary where keys are the IDs of the children.
"""
children = {}
for child in element.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
if child.tagName == 'properties':
- self.assert_(child.parentNode is not None,
- 'Encountered <properties> element without a parent')
+ self.assertTrue(
+ child.parentNode is not None,
+ 'Encountered <properties> element without a parent',
+ )
child_id = child.parentNode.getAttribute('name') + '-properties'
else:
- self.assert_(child.tagName in self.identifying_attribute,
- 'Encountered unknown element <%s>' % child.tagName)
+ self.assertTrue(
+ child.tagName in self.identifying_attribute,
+ 'Encountered unknown element <%s>' % child.tagName,
+ )
child_id = child.getAttribute(
- self.identifying_attribute[child.tagName])
- self.assert_(child_id not in children)
+ self.identifying_attribute[child.tagName]
+ )
+ self.assertNotIn(child_id, children)
children[child_id] = child
elif child.nodeType in [Node.TEXT_NODE, Node.CDATA_SECTION_NODE]:
if 'detail' not in children:
- if (child.nodeType == Node.CDATA_SECTION_NODE or
- not child.nodeValue.isspace()):
+ if (
+ child.nodeType == Node.CDATA_SECTION_NODE
+ or not child.nodeValue.isspace()
+ ):
children['detail'] = child.ownerDocument.createCDATASection(
- child.nodeValue)
+ child.nodeValue
+ )
else:
children['detail'].nodeValue += child.nodeValue
else:
@@ -151,7 +184,8 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
return children
def NormalizeXml(self, element):
- """
+ """Normalizes XML that may change from run to run.
+
Normalizes Google Test's XML output to eliminate references to transient
information that may change from run to run.
@@ -168,6 +202,9 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
file's basename and a single asterisk for the line number.
* The directory names in file paths are removed.
* The stack traces are removed.
+
+ Args:
+ element: DOM element to normalize
"""
if element.tagName == 'testcase':
@@ -176,11 +213,14 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
source_file.value = re.sub(r'^.*[/\\](.*)', '\\1', source_file.value)
if element.tagName in ('testsuites', 'testsuite', 'testcase'):
timestamp = element.getAttributeNode('timestamp')
- timestamp.value = re.sub(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d\d\d$',
- '*', timestamp.value)
+ timestamp.value = re.sub(
+ r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d\d\d$', '*', timestamp.value
+ )
if element.tagName in ('testsuites', 'testsuite', 'testcase'):
time = element.getAttributeNode('time')
- time.value = re.sub(r'^\d+(\.\d+)?$', '*', time.value)
+ # The value for exact N seconds has a traling decimal point (e.g., "10."
+ # instead of "10")
+ time.value = re.sub(r'^\d+\.(\d+)?$', '*', time.value)
type_param = element.getAttributeNode('type_param')
if type_param and type_param.value:
type_param.value = '*'
@@ -194,8 +234,9 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
# Replaces the source line information with a normalized form.
cdata = re.sub(source_line_pat, '\\1*\n', child.nodeValue)
# Removes the actual stack trace.
- child.nodeValue = re.sub(r'Stack trace:\n(.|\n)*',
- 'Stack trace:\n*', cdata)
+ child.nodeValue = re.sub(
+ r'Stack trace:\n(.|\n)*', 'Stack trace:\n*', cdata
+ )
for child in element.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
self.NormalizeXml(child)