summaryrefslogtreecommitdiffstats
path: root/googletest
diff options
context:
space:
mode:
Diffstat (limited to 'googletest')
-rw-r--r--googletest/CMakeLists.txt3
-rw-r--r--googletest/cmake/internal_utils.cmake4
-rw-r--r--googletest/docs/advanced.md177
-rw-r--r--googletest/docs/faq.md16
-rw-r--r--googletest/docs/pkgconfig.md2
-rw-r--r--googletest/docs/primer.md2
-rw-r--r--googletest/include/gtest/gtest-matchers.h18
-rw-r--r--googletest/include/gtest/gtest-param-test.h3
-rw-r--r--googletest/include/gtest/gtest-printers.h103
-rw-r--r--googletest/include/gtest/gtest.h3
-rw-r--r--googletest/include/gtest/internal/gtest-internal.h242
-rw-r--r--googletest/include/gtest/internal/gtest-param-util.h27
-rw-r--r--googletest/include/gtest/internal/gtest-port.h9
-rw-r--r--googletest/include/gtest/internal/gtest-string.h3
-rw-r--r--googletest/src/gtest-death-test.cc41
-rw-r--r--googletest/src/gtest-filepath.cc12
-rw-r--r--googletest/src/gtest-port.cc7
-rw-r--r--googletest/src/gtest-printers.cc6
-rw-r--r--googletest/src/gtest.cc120
-rw-r--r--googletest/test/googletest-death-test-test.cc24
-rw-r--r--googletest/test/googletest-output-test-golden-lin.txt38
-rw-r--r--googletest/test/googletest-port-test.cc10
-rw-r--r--googletest/test/googletest-printers-test.cc173
-rw-r--r--googletest/test/googletest-shuffle-test_.cc2
-rw-r--r--googletest/test/gtest-typed-test_test.cc8
-rw-r--r--googletest/test/gtest_list_output_unittest.py155
-rw-r--r--googletest/test/gtest_list_output_unittest_.cc30
-rw-r--r--googletest/test/gtest_unittest.cc346
-rwxr-xr-xgoogletest/test/gtest_xml_test_utils.py2
29 files changed, 1234 insertions, 352 deletions
diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt
index f538c967..cf63c602 100644
--- a/googletest/CMakeLists.txt
+++ b/googletest/CMakeLists.txt
@@ -320,6 +320,9 @@ $env:Path = \"$project_bin;$env:Path\"
cxx_executable(googletest-uninitialized-test_ test gtest)
py_test(googletest-uninitialized-test)
+ cxx_executable(gtest_list_output_unittest_ test gtest)
+ py_test(gtest_list_output_unittest)
+
cxx_executable(gtest_xml_outfile1_test_ test gtest_main)
cxx_executable(gtest_xml_outfile2_test_ test gtest_main)
py_test(gtest_xml_outfiles_test)
diff --git a/googletest/cmake/internal_utils.cmake b/googletest/cmake/internal_utils.cmake
index 2f70f0b0..b3e8b819 100644
--- a/googletest/cmake/internal_utils.cmake
+++ b/googletest/cmake/internal_utils.cmake
@@ -188,6 +188,10 @@ function(cxx_library_with_type name type cxx_flags)
endif()
target_link_libraries(${name} PUBLIC ${threads_spec})
endif()
+
+ if (NOT "${CMAKE_VERSION}" VERSION_LESS "3.8")
+ target_compile_features(${name} PUBLIC cxx_std_11)
+ endif()
endfunction()
########################################################################
diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md
index 60c1a2b0..89aca1cf 100644
--- a/googletest/docs/advanced.md
+++ b/googletest/docs/advanced.md
@@ -2,6 +2,8 @@
<!-- GOOGLETEST_CM0016 DO NOT DELETE -->
+<!-- GOOGLETEST_CM0035 DO NOT DELETE -->
+
## Introduction
Now that you have read the [googletest Primer](primer.md) and learned how to
@@ -187,11 +189,11 @@ write a predicate function that returns `AssertionResult` instead of `bool`. For
example, if you define `IsEven()` as:
```c++
-::testing::AssertionResult IsEven(int n) {
+testing::AssertionResult IsEven(int n) {
if ((n % 2) == 0)
- return ::testing::AssertionSuccess();
+ return testing::AssertionSuccess();
else
- return ::testing::AssertionFailure() << n << " is odd";
+ return testing::AssertionFailure() << n << " is odd";
}
```
@@ -225,11 +227,11 @@ are fine with making the predicate slower in the success case, you can supply a
success message:
```c++
-::testing::AssertionResult IsEven(int n) {
+testing::AssertionResult IsEven(int n) {
if ((n % 2) == 0)
- return ::testing::AssertionSuccess() << n << " is even";
+ return testing::AssertionSuccess() << n << " is even";
else
- return ::testing::AssertionFailure() << n << " is odd";
+ return testing::AssertionFailure() << n << " is odd";
}
```
@@ -260,14 +262,14 @@ a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a *predicate-formatter*
(`pred_formatn`), which is a function or functor with the signature:
```c++
-::testing::AssertionResult PredicateFormattern(const char* expr1,
- const char* expr2,
- ...
- const char* exprn,
- T1 val1,
- T2 val2,
- ...
- Tn valn);
+testing::AssertionResult PredicateFormattern(const char* expr1,
+ const char* expr2,
+ ...
+ const char* exprn,
+ T1 val1,
+ T2 val2,
+ ...
+ Tn valn);
```
where `val1`, `val2`, ..., and `valn` are the values of the predicate arguments,
@@ -285,13 +287,13 @@ used with `EXPECT_PRED2()`:
int SmallestPrimeCommonDivisor(int m, int n) { ... }
// A predicate-formatter for asserting that two integers are mutually prime.
-::testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
- const char* n_expr,
- int m,
- int n) {
- if (MutuallyPrime(m, n)) return ::testing::AssertionSuccess();
+testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
+ const char* n_expr,
+ int m,
+ int n) {
+ if (MutuallyPrime(m, n)) return testing::AssertionSuccess();
- return ::testing::AssertionFailure() << m_expr << " and " << n_expr
+ return testing::AssertionFailure() << m_expr << " and " << n_expr
<< " (" << m << " and " << n << ") are not mutually prime, "
<< "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n);
}
@@ -360,8 +362,8 @@ that can be used in predicate assertion macros (e.g. `EXPECT_PRED_FORMAT2`,
etc).
```c++
-EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2);
-EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2);
+EXPECT_PRED_FORMAT2(testing::FloatLE, val1, val2);
+EXPECT_PRED_FORMAT2(testing::DoubleLE, val1, val2);
```
Verifies that `val1` is less than, or almost equal to, `val2`. You can replace
@@ -369,9 +371,11 @@ Verifies that `val1` is less than, or almost equal to, `val2`. You can replace
### Asserting Using gMock Matchers
-[gMock](../../googlemock) comes with a library of matchers for validating
-arguments passed to mock objects. A gMock *matcher* is basically a predicate
-that knows how to describe itself. It can be used in these assertion macros:
+[gMock](../../googlemock) comes with
+[a library of matchers](../../googlemock/docs/cheat_sheet.md#MatcherList) for
+validating arguments passed to mock objects. A gMock *matcher* is basically a
+predicate that knows how to describe itself. It can be used in these assertion
+macros:
<!-- mdformat off(github rendering does not support multiline tables) -->
@@ -429,7 +433,7 @@ its DOM tree matches an
```c++
// Currently still in //template/prototemplate/testing:xpath_matcher
#include "template/prototemplate/testing/xpath_matcher.h"
-using prototemplate::testing::MatchesXPath;
+using ::prototemplate::testing::MatchesXPath;
EXPECT_THAT(html_string, MatchesXPath("//a[text()='click here']"));
```
@@ -476,7 +480,7 @@ instantiated. For example, given:
```c++
template <typename T> class Foo {
public:
- void Bar() { ::testing::StaticAssertTypeEq<int, T>(); }
+ void Bar() { testing::StaticAssertTypeEq<int, T>(); }
};
```
@@ -524,8 +528,8 @@ a `SetUp`/`TearDown` function; see
[constructor/destructor vs. `SetUp`/`TearDown`](faq.md#CtorVsSetUp)
WARNING: A fatal assertion in a helper function (private void-returning method)
-called from a constructor or destructor does not does not terminate the current
-test, as your intuition might suggest: it merely returns from the constructor or
+called from a constructor or destructor does not terminate the current test, as
+your intuition might suggest: it merely returns from the constructor or
destructor early, possibly leaving your object in a partially-constructed or
partially-destructed state! You almost certainly want to `abort` or use
`SetUp`/`TearDown` instead.
@@ -605,7 +609,7 @@ call `::testing::PrintToString(x)`, which returns an `std::string`:
vector<pair<Bar, int> > bar_ints = GetBarIntVector();
EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
- << "bar_ints = " << ::testing::PrintToString(bar_ints);
+ << "bar_ints = " << testing::PrintToString(bar_ints);
```
## Death Tests
@@ -674,7 +678,7 @@ This expression is `true` if the program exited normally with the given exit
code.
```c++
-::testing::KilledBySignal(signal_number) // Not available on Windows.
+testing::KilledBySignal(signal_number) // Not available on Windows.
```
This expression is `true` if the program was killed by the given signal.
@@ -707,11 +711,11 @@ TEST(MyDeathTest, Foo) {
}
TEST(MyDeathTest, NormalExit) {
- EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success");
+ EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success");
}
TEST(MyDeathTest, KillMyself) {
- EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL),
+ EXPECT_EXIT(KillMyself(), testing::KilledBySignal(SIGKILL),
"Sending myself unblockable signal");
}
```
@@ -738,7 +742,7 @@ If a test fixture class is shared by normal tests and death tests, you can use
duplicating its code:
```c++
-class FooTest : public ::testing::Test { ... };
+class FooTest : public testing::Test { ... };
using FooDeathTest = FooTest;
@@ -798,7 +802,7 @@ limited syntax only.
Under the hood, `ASSERT_EXIT()` spawns a new process and executes the death test
statement in that process. The details of how precisely that happens depend on
-the platform and the variable ::testing::GTEST_FLAG(death_test_style) (which is
+the platform and the variable `::testing::GTEST_FLAG(death_test_style)` (which is
initialized from the command-line flag `--gtest_death_test_style`).
* On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the
@@ -863,13 +867,13 @@ restored afterwards, so you need not do that yourself. For example:
```c++
int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- ::testing::FLAGS_gtest_death_test_style = "fast";
+ testing::InitGoogleTest(&argc, argv);
+ testing::FLAGS_gtest_death_test_style = "fast";
return RUN_ALL_TESTS();
}
TEST(MyDeathTest, TestOne) {
- ::testing::FLAGS_gtest_death_test_style = "threadsafe";
+ testing::FLAGS_gtest_death_test_style = "threadsafe";
// This test is run in the "threadsafe" style:
ASSERT_DEATH(ThisShouldDie(), "");
}
@@ -909,6 +913,12 @@ handlers registered with `pthread_atfork(3)`.
## Using Assertions in Sub-routines
+Note: If you want to put a series of test assertions in a subroutine to check
+for a complex condition, consider using
+[a custom GMock matcher](../../googlemock/docs/cook_book.md#NewMatchers)
+instead. This lets you provide a more readable error message in case of failure
+and avoid all of the issues described below.
+
### Adding Traces to Assertions
If a test sub-routine is called from several places, when an assertion inside it
@@ -1100,7 +1110,7 @@ If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test
fixture, you must add the `::testing::Test::` prefix, as in:
```c++
-if (::testing::Test::HasFatalFailure()) return;
+if (testing::Test::HasFatalFailure()) return;
```
Similarly, `HasNonfatalFailure()` returns `true` if the current test has at
@@ -1179,7 +1189,7 @@ state to its original value before passing control to the next test.
Here's an example of per-test-suite set-up and tear-down:
```c++
-class FooTest : public ::testing::Test {
+class FooTest : public testing::Test {
protected:
// Per-test-suite set-up.
// Called before the first test in this test suite.
@@ -1230,7 +1240,7 @@ First, you subclass the `::testing::Environment` class to define a test
environment, which knows how to set-up and tear-down:
```c++
-class Environment : public ::testing::Environment {
+class Environment : public testing::Environment {
public:
~Environment() override {}
@@ -1268,8 +1278,8 @@ probably in `main()`. If you use `gtest_main`, you need to call this before
variable like this:
```c++
-::testing::Environment* const foo_env =
- ::testing::AddGlobalTestEnvironment(new FooEnvironment);
+testing::Environment* const foo_env =
+ testing::AddGlobalTestEnvironment(new FooEnvironment);
```
However, we strongly recommend you to write your own `main()` and call
@@ -1375,15 +1385,11 @@ INSTANTIATE_TEST_SUITE_P(InstantiationName,
NOTE: The code above must be placed at global or namespace scope, not at
function scope.
-NOTE: Don't forget this step! If you do your test will silently pass, but none
-of its suites will ever run!
-
-There is work in progress to make omitting `INSTANTIATE_TEST_SUITE_P` show up
-under the `GoogleTestVerification` test suite and to then make that an error.
-If you have a test suite where that omission is not an error, for example it is
-in a library that may be linked in for other reason or where the list of test
-cases is dynamic and may be empty, then this check can be suppressed by tagging
-the test suite:
+Per default, every `TEST_P` without a corresponding `INSTANTIATE_TEST_SUITE_P`
+causes a failing test in test suite `GoogleTestVerification`. If you have a test
+suite where that omission is not an error, for example it is in a library that
+may be linked in for other reason or where the list of test cases is dynamic and
+may be empty, then this check can be suppressed by tagging the test suite:
```c++
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest);
@@ -1490,7 +1496,7 @@ for conciseness:
```c++
enum class MyType { MY_FOO = 0, MY_BAR = 1 };
-class MyTestSuite : public testing::TestWithParam<std::tuple<MyType, string>> {
+class MyTestSuite : public testing::TestWithParam<std::tuple<MyType, std::string>> {
};
INSTANTIATE_TEST_SUITE_P(
@@ -1499,7 +1505,7 @@ INSTANTIATE_TEST_SUITE_P(
testing::Values(MyType::VALUE_0, MyType::VALUE_1),
testing::ValuesIn("", "")),
[](const testing::TestParamInfo<MyTestSuite::ParamType>& info) {
- string name = absl::StrCat(
+ std::string name = absl::StrCat(
std::get<0>(info.param) == MY_FOO ? "Foo" : "Bar", "_",
std::get<1>(info.param));
absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '_');
@@ -1529,10 +1535,10 @@ Remember to derive it from `::testing::Test`:
```c++
template <typename T>
-class FooTest : public ::testing::Test {
+class FooTest : public testing::Test {
public:
...
- typedef std::list<T> List;
+ using List = std::list<T>;
static T shared_;
T value_;
};
@@ -1597,7 +1603,7 @@ First, define a fixture class template, as we did with typed tests:
```c++
template <typename T>
-class FooTest : public ::testing::Test {
+class FooTest : public testing::Test {
...
};
```
@@ -1636,7 +1642,7 @@ put the above code in a header file, you can `#include` it in multiple C++
source files and instantiate it multiple times.
```c++
-typedef ::testing::Types<char, int, unsigned int> MyTypes;
+using MyTypes = ::testing::Types<char, int, unsigned int>;
INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
```
@@ -1755,7 +1761,7 @@ To test them, we use the following special techniques:
```c++
namespace my_namespace {
- class FooTest : public ::testing::Test {
+ class FooTest : public testing::Test {
protected:
...
};
@@ -1850,7 +1856,7 @@ undefined.
Use case example:
```c++
-class MyFixture : public ::testing::Test {
+class MyFixture : public testing::Test {
public:
// All of these optional, just like in regular macro usage.
static void SetUpTestSuite() { ... }
@@ -1870,7 +1876,7 @@ class MyTest : public MyFixture {
void RegisterMyTests(const std::vector<int>& values) {
for (int v : values) {
- ::testing::RegisterTest(
+ testing::RegisterTest(
"MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
std::to_string(v).c_str(),
__FILE__, __LINE__,
@@ -1915,8 +1921,8 @@ To obtain a `TestInfo` object for the currently running test, call
```c++
// Gets information about the currently running test.
// Do NOT delete the returned object - it's managed by the UnitTest class.
- const ::testing::TestInfo* const test_info =
- ::testing::UnitTest::GetInstance()->current_test_info();
+ const testing::TestInfo* const test_info =
+ testing::UnitTest::GetInstance()->current_test_info();
printf("We are in test %s of test suite %s.\n",
test_info->name(),
@@ -1962,15 +1968,15 @@ interesting information about the event and the test program's state.
Here's an example:
```c++
- class MinimalistPrinter : public ::testing::EmptyTestEventListener {
+ class MinimalistPrinter : public testing::EmptyTestEventListener {
// Called before a test starts.
- virtual void OnTestStart(const ::testing::TestInfo& test_info) {
+ virtual void OnTestStart(const testing::TestInfo& test_info) {
printf("*** Test %s.%s starting.\n",
test_info.test_suite_name(), test_info.name());
}
// Called after a failed assertion or a SUCCESS().
- virtual void OnTestPartResult(const ::testing::TestPartResult& test_part_result) {
+ virtual void OnTestPartResult(const testing::TestPartResult& test_part_result) {
printf("%s in %s:%d\n%s\n",
test_part_result.failed() ? "*** Failure" : "Success",
test_part_result.file_name(),
@@ -1979,7 +1985,7 @@ Here's an example:
}
// Called after a test ends.
- virtual void OnTestEnd(const ::testing::TestInfo& test_info) {
+ virtual void OnTestEnd(const testing::TestInfo& test_info) {
printf("*** Test %s.%s ending.\n",
test_info.test_suite_name(), test_info.name());
}
@@ -1995,10 +2001,10 @@ the "s" at the end of the name) in your `main()` function, before calling
```c++
int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
+ testing::InitGoogleTest(&argc, argv);
// Gets hold of the event listener list.
- ::testing::TestEventListeners& listeners =
- ::testing::UnitTest::GetInstance()->listeners();
+ testing::TestEventListeners& listeners =
+ testing::UnitTest::GetInstance()->listeners();
// Adds a listener to the end. googletest takes the ownership.
listeners.Append(new MinimalistPrinter);
return RUN_ALL_TESTS();
@@ -2143,7 +2149,7 @@ will still be compiled:
// Tests that Foo does Abc.
TEST(FooTest, DISABLED_DoesAbc) { ... }
-class DISABLED_BarTest : public ::testing::Test { ... };
+class DISABLED_BarTest : public testing::Test { ... };
// Tests that Bar does Xyz.
TEST_F(DISABLED_BarTest, DoesXyz) { ... }
@@ -2603,3 +2609,32 @@ to be handled by the debugger, such that you can examine the call stack when an
exception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS`
environment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when
running the tests.
+
+### Sanitizer Integration
+
+The
+[Undefined Behavior Sanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html),
+[Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer),
+and
+[Thread Sanitizer](https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual)
+all provide weak functions that you can override to trigger explicit failures
+when they detect sanitizer errors, such as creating a reference from `nullptr`.
+To override these functions, place definitions for them in a source file that
+you compile as part of your main binary:
+
+```
+extern "C" {
+void __ubsan_on_report() {
+ FAIL() << "Encountered an undefined behavior sanitizer error";
+}
+void __asan_on_error() {
+ FAIL() << "Encountered an address sanitizer error";
+}
+void __tsan_on_report() {
+ FAIL() << "Encountered a thread sanitizer error";
+}
+} // extern "C"
+```
+
+After compiling your project with one of the sanitizers enabled, if a particular
+test triggers a sanitizer error, googletest will report that it failed.
diff --git a/googletest/docs/faq.md b/googletest/docs/faq.md
index 05ecdd7d..3ece95bc 100644
--- a/googletest/docs/faq.md
+++ b/googletest/docs/faq.md
@@ -2,8 +2,14 @@
<!-- GOOGLETEST_CM0014 DO NOT DELETE -->
+<!-- GOOGLETEST_CM0035 DO NOT DELETE -->
+
## Why should test suite names and test names not contain underscore?
+Note: Googletest reserves underscore (`_`) for special purpose keywords, such as
+[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition
+to the following rationale.
+
Underscore (`_`) is special, as C++ reserves the following to be used by the
compiler and the standard library:
@@ -295,7 +301,7 @@ program from the beginning in the child process. Therefore make sure your
program can run side-by-side with itself and is deterministic.
In the end, this boils down to good concurrent programming. You have to make
-sure that there is no race conditions or dead locks in your program. No silver
+sure that there are no race conditions or deadlocks in your program. No silver
bullet - sorry!
## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp}
@@ -401,7 +407,7 @@ you can use it in a predicate assertion like this:
ASSERT_PRED1(IsNegative<int>, -5);
```
-Things are more interesting if your template has more than one parameters. The
+Things are more interesting if your template has more than one parameter. The
following won't compile:
```c++
@@ -555,7 +561,7 @@ TEST(MyDeathTest, ComplexExpression) {
"(Func1|Method) failed");
}
-// Death assertions can be used any where in a function. In
+// Death assertions can be used anywhere in a function. In
// particular, they can be inside a loop.
TEST(MyDeathTest, InsideLoop) {
// Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
@@ -597,7 +603,7 @@ However, there are cases where you have to define your own:
## Why does ASSERT_DEATH complain about previous threads that were already joined?
With the Linux pthread library, there is no turning back once you cross the line
-from single thread to multiple threads. The first time you create a thread, a
+from a single thread to multiple threads. The first time you create a thread, a
manager thread is created in addition, so you get 3, not 2, threads. Later when
the thread you create joins the main thread, the thread count decrements by 1,
but the manager thread will never be killed, so you still have 2 threads, which
@@ -612,7 +618,7 @@ runs on, you shouldn't depend on this.
googletest does not interleave tests from different test suites. That is, it
runs all tests in one test suite first, and then runs all tests in the next test
suite, and so on. googletest does this because it needs to set up a test suite
-before the first test in it is run, and tear it down afterwords. Splitting up
+before the first test in it is run, and tear it down afterwards. Splitting up
the test case would require multiple set-up and tear-down processes, which is
inefficient and makes the semantics unclean.
diff --git a/googletest/docs/pkgconfig.md b/googletest/docs/pkgconfig.md
index b9bef3fd..aed4ad45 100644
--- a/googletest/docs/pkgconfig.md
+++ b/googletest/docs/pkgconfig.md
@@ -1,5 +1,7 @@
## Using GoogleTest from various build systems
+<!-- GOOGLETEST_CM0035 DO NOT DELETE -->
+
GoogleTest comes with pkg-config files that can be used to determine all
necessary flags for compiling and linking to GoogleTest (and GoogleMock).
Pkg-config is a standardised plain-text format containing
diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md
index 2f459fd7..ed44369a 100644
--- a/googletest/docs/primer.md
+++ b/googletest/docs/primer.md
@@ -1,5 +1,7 @@
# Googletest Primer
+<!-- GOOGLETEST_CM0035 DO NOT DELETE -->
+
## Introduction: Why googletest?
*googletest* helps you write better C++ tests.
diff --git a/googletest/include/gtest/gtest-matchers.h b/googletest/include/gtest/gtest-matchers.h
index a61cef40..04cc63de 100644
--- a/googletest/include/gtest/gtest-matchers.h
+++ b/googletest/include/gtest/gtest-matchers.h
@@ -612,6 +612,10 @@ class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
static const char* NegatedDesc() { return "isn't >="; }
};
+template <typename T, typename = typename std::enable_if<
+ std::is_constructible<std::string, T>::value>::type>
+using StringLike = T;
+
// Implements polymorphic matchers MatchesRegex(regex) and
// ContainsRegex(regex), which can be used as a Matcher<T> as long as
// T can be converted to a string.
@@ -672,9 +676,10 @@ inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
const internal::RE* regex) {
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
}
-inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
- const std::string& regex) {
- return MatchesRegex(new internal::RE(regex));
+template <typename T = std::string>
+PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
+ const internal::StringLike<T>& regex) {
+ return MatchesRegex(new internal::RE(std::string(regex)));
}
// Matches a string that contains regular expression 'regex'.
@@ -683,9 +688,10 @@ inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
const internal::RE* regex) {
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
}
-inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
- const std::string& regex) {
- return ContainsRegex(new internal::RE(regex));
+template <typename T = std::string>
+PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
+ const internal::StringLike<T>& regex) {
+ return ContainsRegex(new internal::RE(std::string(regex)));
}
// Creates a polymorphic matcher that matches anything equal to x.
diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h
index 5b039df9..9a60b766 100644
--- a/googletest/include/gtest/gtest-param-test.h
+++ b/googletest/include/gtest/gtest-param-test.h
@@ -428,7 +428,8 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
->AddTestPattern( \
GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \
new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
- test_suite_name, test_name)>()); \
+ test_suite_name, test_name)>(), \
+ ::testing::internal::CodeLocation(__FILE__, __LINE__)); \
return 0; \
} \
static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h
index 308b0eb2..463f0aff 100644
--- a/googletest/include/gtest/gtest-printers.h
+++ b/googletest/include/gtest/gtest-printers.h
@@ -188,51 +188,43 @@ struct PointerPrinter {
}
};
-namespace internal_stream {
+namespace internal_stream_operator_without_lexical_name_lookup {
-struct Sentinel;
-template <typename Char, typename CharTraits, typename T>
-Sentinel* operator<<(::std::basic_ostream<Char, CharTraits>& os, const T& x);
-
-// Check if the user has a user-defined operator<< for their type.
-//
-// We put this in its own namespace to inject a custom operator<< that allows us
-// to probe the type's operator.
-//
-// Note that this operator<< takes a generic std::basic_ostream<Char,
-// CharTraits> type instead of the more restricted std::ostream. If
-// we define it to take an std::ostream instead, we'll get an
-// "ambiguous overloads" compiler error when trying to print a type
-// Foo that supports streaming to std::basic_ostream<Char,
-// CharTraits>, as the compiler cannot tell whether
-// operator<<(std::ostream&, const T&) or
-// operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
-// specific.
-template <typename T>
-constexpr bool UseStreamOperator() {
- return !std::is_same<decltype(std::declval<std::ostream&>()
- << std::declval<const T&>()),
- Sentinel*>::value;
-}
-
-} // namespace internal_stream
+// The presence of an operator<< here will terminate lexical scope lookup
+// straight away (even though it cannot be a match because of its argument
+// types). Thus, the two operator<< calls in StreamPrinter will find only ADL
+// candidates.
+struct LookupBlocker {};
+void operator<<(LookupBlocker, LookupBlocker);
struct StreamPrinter {
- template <typename T, typename = typename std::enable_if<
- internal_stream::UseStreamOperator<T>()>::type>
+ template <typename T,
+ // Don't accept member pointers here. We'd print them via implicit
+ // conversion to bool, which isn't useful.
+ typename = typename std::enable_if<
+ !std::is_member_pointer<T>::value>::type,
+ // Only accept types for which we can find a streaming operator via
+ // ADL (possibly involving implicit conversions).
+ typename = decltype(std::declval<std::ostream&>()
+ << std::declval<const T&>())>
static void PrintValue(const T& value, ::std::ostream* os) {
+ // Call streaming operator found by ADL, possibly with implicit conversions
+ // of the arguments.
*os << value;
}
};
+} // namespace internal_stream_operator_without_lexical_name_lookup
+
struct ProtobufPrinter {
// We print a protobuf using its ShortDebugString() when the string
// doesn't exceed this many characters; otherwise we print it using
// DebugString() for better readability.
static const size_t kProtobufOneLinerMaxLength = 50;
- template <typename T, typename = typename std::enable_if<
- internal::IsAProtocolMessage<T>::value>::type>
+ template <typename T,
+ typename = typename std::enable_if<
+ internal::HasDebugStringAndShortDebugString<T>::value>::type>
static void PrintValue(const T& value, ::std::ostream* os) {
std::string pretty_str = value.ShortDebugString();
if (pretty_str.length() > kProtobufOneLinerMaxLength) {
@@ -303,7 +295,8 @@ template <typename T>
void PrintWithFallback(const T& value, ::std::ostream* os) {
using Printer = typename FindFirstPrinter<
T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
- StreamPrinter, ProtobufPrinter, ConvertibleToIntegerPrinter,
+ internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
+ ProtobufPrinter, ConvertibleToIntegerPrinter,
ConvertibleToStringViewPrinter, FallbackPrinter>::type;
Printer::PrintValue(value, os);
}
@@ -356,6 +349,14 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
+#ifdef __cpp_char8_t
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
+#endif
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
@@ -373,6 +374,14 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
+#ifdef __cpp_char8_t
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
+#endif
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
#if GTEST_HAS_STD_WSTRING
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
@@ -449,6 +458,16 @@ inline void PrintTo(bool x, ::std::ostream* os) {
// is implemented as an unsigned type.
GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
+GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
+inline void PrintTo(char16_t c, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<char32_t>(c), os);
+}
+#ifdef __cpp_char8_t
+inline void PrintTo(char8_t c, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<char32_t>(c), os);
+}
+#endif
+
// Overloads for C strings.
GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
inline void PrintTo(char* s, ::std::ostream* os) {
@@ -469,6 +488,26 @@ inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
inline void PrintTo(unsigned char* s, ::std::ostream* os) {
PrintTo(ImplicitCast_<const void*>(s), os);
}
+#ifdef __cpp_char8_t
+inline void PrintTo(const char8_t* s, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<const void*>(s), os);
+}
+inline void PrintTo(char8_t* s, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<const void*>(s), os);
+}
+#endif
+inline void PrintTo(const char16_t* s, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<const void*>(s), os);
+}
+inline void PrintTo(char16_t* s, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<const void*>(s), os);
+}
+inline void PrintTo(const char32_t* s, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<const void*>(s), os);
+}
+inline void PrintTo(char32_t* s, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<const void*>(s), os);
+}
// MSVC can be configured to define wchar_t as a typedef of unsigned
// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h
index a0942b49..b3d40416 100644
--- a/googletest/include/gtest/gtest.h
+++ b/googletest/include/gtest/gtest.h
@@ -434,7 +434,8 @@ class GTEST_API_ Test {
// class.
static void TearDownTestSuite() {}
- // Legacy API is deprecated but still available
+ // Legacy API is deprecated but still available. Use SetUpTestSuite and
+ // TearDownTestSuite instead.
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
static void TearDownTestCase() {}
static void SetUpTestCase() {}
diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h
index 028f21eb..d990c0f6 100644
--- a/googletest/include/gtest/internal/gtest-internal.h
+++ b/googletest/include/gtest/internal/gtest-internal.h
@@ -287,7 +287,7 @@ class FloatingPoint {
//
// See the following article for more details on ULP:
// http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
- static const size_t kMaxUlps = 4;
+ static const uint32_t kMaxUlps = 4;
// Constructs a FloatingPoint from a raw floating-point number.
//
@@ -520,6 +520,7 @@ struct SuiteApiResolver : T {
static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,
int line_num) {
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
SetUpTearDownSuiteFuncType test_case_fp =
GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);
SetUpTearDownSuiteFuncType test_suite_fp =
@@ -531,10 +532,16 @@ struct SuiteApiResolver : T {
<< filename << ":" << line_num;
return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
+#else
+ (void)(filename);
+ (void)(line_num);
+ return &T::SetUpTestSuite;
+#endif
}
static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,
int line_num) {
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
SetUpTearDownSuiteFuncType test_case_fp =
GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);
SetUpTearDownSuiteFuncType test_suite_fp =
@@ -546,6 +553,11 @@ struct SuiteApiResolver : T {
<< filename << ":" << line_num;
return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
+#else
+ (void)(filename);
+ (void)(line_num);
+ return &T::TearDownTestSuite;
+#endif
}
};
@@ -880,11 +892,34 @@ class GTEST_API_ Random {
#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
typename std::remove_const<typename std::remove_reference<T>::type>::type
-// IsAProtocolMessage<T>::value is a compile-time bool constant that's
-// true if and only if T is type proto2::MessageLite or a subclass of it.
+// HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant
+// that's true if and only if T has methods DebugString() and ShortDebugString()
+// that return std::string.
template <typename T>
-struct IsAProtocolMessage
- : public std::is_convertible<const T*, const ::proto2::MessageLite*> {};
+class HasDebugStringAndShortDebugString {
+ private:
+ template <typename C>
+ static constexpr auto CheckDebugString(C*) -> typename std::is_same<
+ std::string, decltype(std::declval<const C>().DebugString())>::type;
+ template <typename>
+ static constexpr std::false_type CheckDebugString(...);
+
+ template <typename C>
+ static constexpr auto CheckShortDebugString(C*) -> typename std::is_same<
+ std::string, decltype(std::declval<const C>().ShortDebugString())>::type;
+ template <typename>
+ static constexpr std::false_type CheckShortDebugString(...);
+
+ using HasDebugStringType = decltype(CheckDebugString<T>(nullptr));
+ using HasShortDebugStringType = decltype(CheckShortDebugString<T>(nullptr));
+
+ public:
+ static constexpr bool value =
+ HasDebugStringType::value && HasShortDebugStringType::value;
+};
+
+template <typename T>
+constexpr bool HasDebugStringAndShortDebugString<T>::value;
// When the compiler sees expression IsContainerTest<C>(0), if C is an
// STL-style container class, the first overload of IsContainerTest
@@ -1143,12 +1178,18 @@ struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
// Backport of std::make_index_sequence.
// It uses O(ln(N)) instantiation depth.
template <size_t N>
-struct MakeIndexSequence
- : DoubleSequence<N % 2 == 1, typename MakeIndexSequence<N / 2>::type,
+struct MakeIndexSequenceImpl
+ : DoubleSequence<N % 2 == 1, typename MakeIndexSequenceImpl<N / 2>::type,
N / 2>::type {};
template <>
-struct MakeIndexSequence<0> : IndexSequence<> {};
+struct MakeIndexSequenceImpl<0> : IndexSequence<> {};
+
+template <size_t N>
+using MakeIndexSequence = typename MakeIndexSequenceImpl<N>::type;
+
+template <typename... T>
+using IndexSequenceFor = typename MakeIndexSequence<sizeof...(T)>::type;
template <size_t>
struct Ignore {
@@ -1174,6 +1215,8 @@ struct ElemFromList {
static_cast<T (*)()>(nullptr)...));
};
+struct FlatTupleConstructTag {};
+
template <typename... T>
class FlatTuple;
@@ -1184,7 +1227,9 @@ template <typename... T, size_t I>
struct FlatTupleElemBase<FlatTuple<T...>, I> {
using value_type = typename ElemFromList<I, T...>::type;
FlatTupleElemBase() = default;
- explicit FlatTupleElemBase(value_type t) : value(std::move(t)) {}
+ template <typename Arg>
+ explicit FlatTupleElemBase(FlatTupleConstructTag, Arg&& t)
+ : value(std::forward<Arg>(t)) {}
value_type value;
};
@@ -1196,8 +1241,30 @@ struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
: FlatTupleElemBase<FlatTuple<T...>, Idx>... {
using Indices = IndexSequence<Idx...>;
FlatTupleBase() = default;
- explicit FlatTupleBase(T... t)
- : FlatTupleElemBase<FlatTuple<T...>, Idx>(std::move(t))... {}
+ template <typename... Args>
+ explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args)
+ : FlatTupleElemBase<FlatTuple<T...>, Idx>(FlatTupleConstructTag{},
+ std::forward<Args>(args))... {}
+
+ template <size_t I>
+ const typename ElemFromList<I, T...>::type& Get() const {
+ return FlatTupleElemBase<FlatTuple<T...>, I>::value;
+ }
+
+ template <size_t I>
+ typename ElemFromList<I, T...>::type& Get() {
+ return FlatTupleElemBase<FlatTuple<T...>, I>::value;
+ }
+
+ template <typename F>
+ auto Apply(F&& f) -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
+ return std::forward<F>(f)(Get<Idx>()...);
+ }
+
+ template <typename F>
+ auto Apply(F&& f) const -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
+ return std::forward<F>(f)(Get<Idx>()...);
+ }
};
// Analog to std::tuple but with different tradeoffs.
@@ -1218,17 +1285,17 @@ class FlatTuple
public:
FlatTuple() = default;
- explicit FlatTuple(T... t) : FlatTuple::FlatTupleBase(std::move(t)...) {}
-
- template <size_t I>
- const typename ElemFromList<I, T...>::type& Get() const {
- return static_cast<const FlatTupleElemBase<FlatTuple, I>*>(this)->value;
- }
-
- template <size_t I>
- typename ElemFromList<I, T...>::type& Get() {
- return static_cast<FlatTupleElemBase<FlatTuple, I>*>(this)->value;
- }
+ template <typename... Args,
+ typename = typename std::enable_if<
+ !std::is_same<void(FlatTuple), void(typename std::decay<
+ Args>::type...)>::value &&
+ (sizeof...(T) >= 1)>::type>
+ explicit FlatTuple(Args&&... args)
+ : FlatTuple::FlatTupleBase(FlatTupleConstructTag{},
+ std::forward<Args>(args)...) {}
+
+ using FlatTuple::FlatTupleBase::Apply;
+ using FlatTuple::FlatTupleBase::Get;
};
// Utility functions to be called with static_assert to induce deprecation
@@ -1261,6 +1328,22 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
} // namespace internal
} // namespace testing
+namespace std {
+// Some standard library implementations use `struct tuple_size` and some use
+// `class tuple_size`. Clang warns about the mismatch.
+// https://reviews.llvm.org/D55466
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wmismatched-tags"
+#endif
+template <typename... Ts>
+struct tuple_size<testing::internal::FlatTuple<Ts...>>
+ : std::integral_constant<size_t, sizeof...(Ts)> {};
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+} // namespace std
+
#define GTEST_MESSAGE_AT_(file, line, message, result_type) \
::testing::internal::AssertHelper(result_type, file, line, message) \
= ::testing::Message()
@@ -1291,41 +1374,90 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
} else /* NOLINT */ \
static_assert(true, "") // User must have a semicolon after expansion.
-#define GTEST_TEST_THROW_(statement, expected_exception, fail) \
- GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
- if (::testing::internal::ConstCharPtr gtest_msg = "") { \
- bool gtest_caught_expected = false; \
- try { \
- GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
- } \
- catch (expected_exception const&) { \
- gtest_caught_expected = true; \
- } \
- catch (...) { \
- gtest_msg.value = \
- "Expected: " #statement " throws an exception of type " \
- #expected_exception ".\n Actual: it throws a different type."; \
- goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
- } \
- if (!gtest_caught_expected) { \
- gtest_msg.value = \
- "Expected: " #statement " throws an exception of type " \
- #expected_exception ".\n Actual: it throws nothing."; \
- goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
- } \
- } else \
- GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
- fail(gtest_msg.value)
+#if GTEST_HAS_EXCEPTIONS
+
+namespace testing {
+namespace internal {
+
+class NeverThrown {
+ public:
+ const char* what() const noexcept {
+ return "this exception should never be thrown";
+ }
+};
+
+} // namespace internal
+} // namespace testing
+
+#if GTEST_HAS_RTTI
+
+#define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))
+
+#else // GTEST_HAS_RTTI
+
+#define GTEST_EXCEPTION_TYPE_(e) \
+ std::string { "an std::exception-derived error" }
+
+#endif // GTEST_HAS_RTTI
+
+#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
+ catch (typename std::conditional< \
+ std::is_same<typename std::remove_cv<typename std::remove_reference< \
+ expected_exception>::type>::type, \
+ std::exception>::value, \
+ const ::testing::internal::NeverThrown&, const std::exception&>::type \
+ e) { \
+ gtest_msg.value = "Expected: " #statement \
+ " throws an exception of type " #expected_exception \
+ ".\n Actual: it throws "; \
+ gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
+ gtest_msg.value += " with description \""; \
+ gtest_msg.value += e.what(); \
+ gtest_msg.value += "\"."; \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
+ }
+
+#else // GTEST_HAS_EXCEPTIONS
+
+#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)
+
+#endif // GTEST_HAS_EXCEPTIONS
+
+#define GTEST_TEST_THROW_(statement, expected_exception, fail) \
+ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
+ if (::testing::internal::TrueWithString gtest_msg{}) { \
+ bool gtest_caught_expected = false; \
+ try { \
+ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
+ } catch (expected_exception const&) { \
+ gtest_caught_expected = true; \
+ } \
+ GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
+ catch (...) { \
+ gtest_msg.value = "Expected: " #statement \
+ " throws an exception of type " #expected_exception \
+ ".\n Actual: it throws a different type."; \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
+ } \
+ if (!gtest_caught_expected) { \
+ gtest_msg.value = "Expected: " #statement \
+ " throws an exception of type " #expected_exception \
+ ".\n Actual: it throws nothing."; \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
+ } \
+ } else /*NOLINT*/ \
+ GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
+ : fail(gtest_msg.value.c_str())
#if GTEST_HAS_EXCEPTIONS
-#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
- catch (std::exception const& e) { \
- gtest_msg.value = ( \
- "it throws std::exception-derived exception with description: \"" \
- ); \
- gtest_msg.value += e.what(); \
- gtest_msg.value += "\"."; \
+#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
+ catch (std::exception const& e) { \
+ gtest_msg.value = "it throws "; \
+ gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
+ gtest_msg.value += " with description \""; \
+ gtest_msg.value += e.what(); \
+ gtest_msg.value += "\"."; \
goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
}
@@ -1409,7 +1541,7 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
: public parent_class { \
public: \
- GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
+ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \
~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \
GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
test_name)); \
diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h
index 7f7a13bf..138d372e 100644
--- a/googletest/include/gtest/internal/gtest-param-util.h
+++ b/googletest/include/gtest/internal/gtest-param-util.h
@@ -520,9 +520,10 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
// parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
// test suite base name and DoBar is test base name.
void AddTestPattern(const char* test_suite_name, const char* test_base_name,
- TestMetaFactoryBase<ParamType>* meta_factory) {
- tests_.push_back(std::shared_ptr<TestInfo>(
- new TestInfo(test_suite_name, test_base_name, meta_factory)));
+ TestMetaFactoryBase<ParamType>* meta_factory,
+ CodeLocation code_location) {
+ tests_.push_back(std::shared_ptr<TestInfo>(new TestInfo(
+ test_suite_name, test_base_name, meta_factory, code_location)));
}
// INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
// about a generator.
@@ -589,7 +590,7 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
MakeAndRegisterTestInfo(
test_suite_name.c_str(), test_name_stream.GetString().c_str(),
nullptr, // No type parameter.
- PrintToString(*param_it).c_str(), code_location_,
+ PrintToString(*param_it).c_str(), test_info->code_location,
GetTestSuiteTypeId(),
SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
@@ -610,14 +611,17 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
// with TEST_P macro.
struct TestInfo {
TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
- TestMetaFactoryBase<ParamType>* a_test_meta_factory)
+ TestMetaFactoryBase<ParamType>* a_test_meta_factory,
+ CodeLocation a_code_location)
: test_suite_base_name(a_test_suite_base_name),
test_base_name(a_test_base_name),
- test_meta_factory(a_test_meta_factory) {}
+ test_meta_factory(a_test_meta_factory),
+ code_location(a_code_location) {}
const std::string test_suite_base_name;
const std::string test_base_name;
const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
+ const CodeLocation code_location;
};
using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
// Records data received from INSTANTIATE_TEST_SUITE_P macros:
@@ -779,10 +783,15 @@ 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
+
template <typename... Ts>
class ValueArray {
public:
- ValueArray(Ts... v) : v_{std::move(v)...} {}
+ explicit ValueArray(Ts... v) : v_(std::move(v)...) {}
template <typename T>
operator ParamGenerator<T>() const { // NOLINT
@@ -798,6 +807,10 @@ class ValueArray {
FlatTuple<Ts...> v_;
};
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+
template <typename... T>
class CartesianProductGenerator
: public ParamGeneratorInterface<::std::tuple<T...>> {
diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h
index 6f9c14ae..6b66362f 100644
--- a/googletest/include/gtest/internal/gtest-port.h
+++ b/googletest/include/gtest/internal/gtest-port.h
@@ -2055,15 +2055,15 @@ GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
inline int ChDir(const char* dir) { return chdir(dir); }
#endif
inline FILE* FOpen(const char* path, const char* mode) {
-#if GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS && !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);
std::wstring wide_mode = converter.from_bytes(mode);
return _wfopen(wide_path.c_str(), wide_mode.c_str());
-#else
+#else // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
return fopen(path, mode);
-#endif // GTEST_OS_WINDOWS
+#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
}
#if !GTEST_OS_WINDOWS_MOBILE
inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
@@ -2220,7 +2220,8 @@ using TimeInMillis = int64_t; // Represents time in milliseconds.
// Parses 'str' for a 32-bit signed integer. If successful, writes the result
// to *value and returns true; otherwise leaves *value unchanged and returns
// false.
-bool ParseInt32(const Message& src_text, const char* str, int32_t* value);
+GTEST_API_ bool ParseInt32(const Message& src_text, const char* str,
+ int32_t* value);
// Parses a bool/int32_t/string from the environment variable
// corresponding to the given Google Test flag.
diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h
index 0b2a91a5..323a36e6 100644
--- a/googletest/include/gtest/internal/gtest-string.h
+++ b/googletest/include/gtest/internal/gtest-string.h
@@ -149,6 +149,9 @@ class GTEST_API_ String {
// Formats an int value as "%02d".
static std::string FormatIntWidth2(int value); // "%02d" for width == 2
+ // Formats an int value to given width with leading zeros.
+ static std::string FormatIntWidthN(int value, int width);
+
// Formats an int value as "%X".
static std::string FormatHexInt(int value);
diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc
index 5d1031be..9c54b81f 100644
--- a/googletest/src/gtest-death-test.cc
+++ b/googletest/src/gtest-death-test.cc
@@ -32,6 +32,7 @@
#include "gtest/gtest-death-test.h"
+#include <functional>
#include <utility>
#include "gtest/internal/gtest-port.h"
@@ -1225,21 +1226,9 @@ struct ExecDeathTestArgs {
int close_fd; // File descriptor to close; the read end of a pipe
};
-# if GTEST_OS_MAC
-inline char** GetEnviron() {
- // When Google Test is built as a framework on MacOS X, the environ variable
- // is unavailable. Apple's documentation (man environ) recommends using
- // _NSGetEnviron() instead.
- return *_NSGetEnviron();
-}
-# else
-// Some POSIX platforms expect you to declare environ. extern "C" makes
-// it reside in the global namespace.
+# if GTEST_OS_QNX
extern "C" char** environ;
-inline char** GetEnviron() { return environ; }
-# endif // GTEST_OS_MAC
-
-# if !GTEST_OS_QNX
+# else // GTEST_OS_QNX
// The main function for a threadsafe-style death test child process.
// This function is called in a clone()-ed process and thus must avoid
// any potentially unsafe operations like malloc or libc functions.
@@ -1259,18 +1248,18 @@ static int ExecDeathTestChildMain(void* child_arg) {
return EXIT_FAILURE;
}
- // We can safely call execve() as it's a direct system call. We
+ // We can safely call execv() as it's almost a direct system call. We
// cannot use execvp() as it's a libc function and thus potentially
- // unsafe. Since execve() doesn't search the PATH, the user must
+ // unsafe. Since execv() doesn't search the PATH, the user must
// invoke the test program via a valid path that contains at least
// one path separator.
- execve(args->argv[0], args->argv, GetEnviron());
- DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
+ execv(args->argv[0], args->argv);
+ DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " +
original_dir + " failed: " +
GetLastErrnoDescription());
return EXIT_FAILURE;
}
-# endif // !GTEST_OS_QNX
+# endif // GTEST_OS_QNX
# if GTEST_HAS_CLONE
// Two utility routines that together determine the direction the stack
@@ -1284,19 +1273,24 @@ static int ExecDeathTestChildMain(void* child_arg) {
// correct answer.
static void StackLowerThanAddress(const void* ptr,
bool* result) GTEST_NO_INLINE_;
+// Make sure sanitizers do not tamper with the stack here.
+// Ideally, we want to use `__builtin_frame_address` instead of a local variable
+// address with sanitizer disabled, but it does not work when the
+// compiler optimizes the stack frame out, which happens on PowerPC targets.
// HWAddressSanitizer add a random tag to the MSB of the local variable address,
// making comparison result unpredictable.
+GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
static void StackLowerThanAddress(const void* ptr, bool* result) {
- int dummy;
- *result = (&dummy < ptr);
+ int dummy = 0;
+ *result = std::less<const void*>()(&dummy, ptr);
}
// Make sure AddressSanitizer does not tamper with the stack here.
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
static bool StackGrowsDown() {
- int dummy;
+ int dummy = 0;
bool result;
StackLowerThanAddress(&dummy, &result);
return result;
@@ -1339,8 +1333,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
fd_flags | FD_CLOEXEC));
struct inheritance inherit = {0};
// spawn is a system call.
- child_pid =
- spawn(args.argv[0], 0, nullptr, &inherit, args.argv, GetEnviron());
+ child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ);
// Restores the current working directory.
GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc
index 062b95b1..af297684 100644
--- a/googletest/src/gtest-filepath.cc
+++ b/googletest/src/gtest-filepath.cc
@@ -349,21 +349,19 @@ FilePath FilePath::RemoveTrailingPathSeparator() const {
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
// redundancies that might be in a pathname involving "." or "..".
void FilePath::Normalize() {
- std::string normalized_pathname;
- normalized_pathname.reserve(pathname_.length());
+ auto out = pathname_.begin();
for (const char character : pathname_) {
if (!IsPathSeparator(character)) {
- normalized_pathname.push_back(character);
- } else if (normalized_pathname.empty() ||
- normalized_pathname.back() != kPathSeparator) {
- normalized_pathname.push_back(kPathSeparator);
+ *(out++) = character;
+ } else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {
+ *(out++) = kPathSeparator;
} else {
continue;
}
}
- pathname_ = normalized_pathname;
+ pathname_.erase(out, pathname_.end());
}
} // namespace internal
diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc
index c1802337..3f39f71c 100644
--- a/googletest/src/gtest-port.cc
+++ b/googletest/src/gtest-port.cc
@@ -198,7 +198,8 @@ size_t GetThreadCount() {
if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
return 0;
}
- mib[5] = size / mib[4];
+
+ mib[5] = static_cast<int>(size / static_cast<size_t>(mib[4]));
// populate array of structs
struct kinfo_proc info[mib[5]];
@@ -207,8 +208,8 @@ size_t GetThreadCount() {
}
// exclude empty members
- int nthreads = 0;
- for (size_t i = 0; i < size / mib[4]; i++) {
+ size_t nthreads = 0;
+ for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) {
if (info[i].p_tid != -1)
nthreads++;
}
diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc
index 4e1ccad8..20ce1b86 100644
--- a/googletest/src/gtest-printers.cc
+++ b/googletest/src/gtest-printers.cc
@@ -44,6 +44,7 @@
#include "gtest/gtest-printers.h"
#include <stdio.h>
#include <cctype>
+#include <cstdint>
#include <cwchar>
#include <ostream> // NOLINT
#include <string>
@@ -251,6 +252,11 @@ void PrintTo(wchar_t wc, ostream* os) {
PrintCharAndCodeTo<wchar_t>(wc, os);
}
+void PrintTo(char32_t c, ::std::ostream* os) {
+ *os << std::hex << "U+" << std::uppercase << std::setfill('0') << std::setw(4)
+ << static_cast<uint32_t>(c);
+}
+
// Prints the given array of characters to the ostream. CharType must be either
// char or wchar_t.
// The array starts at begin, the length is len, it may include '\0' characters
diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc
index 5a8999f6..3c32da8b 100644
--- a/googletest/src/gtest.cc
+++ b/googletest/src/gtest.cc
@@ -35,7 +35,6 @@
#include "gtest/gtest-spi.h"
#include <ctype.h>
-#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
@@ -44,6 +43,8 @@
#include <wctype.h>
#include <algorithm>
+#include <chrono> // NOLINT
+#include <cmath>
#include <cstdint>
#include <iomanip>
#include <limits>
@@ -55,8 +56,6 @@
#if GTEST_OS_LINUX
-# define GTEST_HAS_GETTIMEOFDAY_ 1
-
# include <fcntl.h> // NOLINT
# include <limits.h> // NOLINT
# include <sched.h> // NOLINT
@@ -68,7 +67,6 @@
# include <string>
#elif GTEST_OS_ZOS
-# define GTEST_HAS_GETTIMEOFDAY_ 1
# include <sys/time.h> // NOLINT
// On z/OS we additionally need strings.h for strcasecmp.
@@ -94,16 +92,11 @@
# include <sys/stat.h> // NOLINT
# if GTEST_OS_WINDOWS_MINGW
-// MinGW has gettimeofday() but not _ftime64().
-# define GTEST_HAS_GETTIMEOFDAY_ 1
# include <sys/time.h> // NOLINT
# endif // GTEST_OS_WINDOWS_MINGW
#else
-// Assume other platforms have gettimeofday().
-# define GTEST_HAS_GETTIMEOFDAY_ 1
-
// cpplint thinks that the header is already included, so we want to
// silence it.
# include <sys/time.h> // NOLINT
@@ -432,8 +425,8 @@ namespace {
// inserted to report ether an error or a log message.
//
// This configuration bit will likely be removed at some point.
-constexpr bool kErrorOnUninstantiatedParameterizedTest = false;
-constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = false;
+constexpr bool kErrorOnUninstantiatedParameterizedTest = true;
+constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true;
// A test that fails at a given file/line location with a given message.
class FailureTest : public Test {
@@ -497,7 +490,7 @@ void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
"removed but the rest got left behind.";
std::string message =
- "Paramaterized test suite " + name +
+ "Parameterized test suite " + name +
(has_test_p ? kMissingInstantiation : kMissingTestCase) +
"\n\n"
"To suppress this error for this test suite, insert the following line "
@@ -505,7 +498,7 @@ void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
"\n\n"
"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");";
- std::string full_name = "UninstantiatedParamaterizedTestSuite<" + name + ">";
+ std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
RegisterTest( //
"GoogleTestVerification", full_name.c_str(),
nullptr, // No type parameter.
@@ -552,7 +545,7 @@ void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
if (ignored.find(testcase.first) != ignored.end()) continue;
std::string message =
- "Type paramaterized test suite " + testcase.first +
+ "Type parameterized test suite " + testcase.first +
" is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
"via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
"\n\n"
@@ -562,13 +555,13 @@ void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
"utilities.)"
"\n\n"
"To suppress this error for this test suite, insert the following line "
- "(in a non-header) in the namespace it is definedin in:"
+ "(in a non-header) in the namespace it is defined in:"
"\n\n"
"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
testcase.first + ");";
std::string full_name =
- "UninstantiatedTypeParamaterizedTestSuite<" + testcase.first + ">";
+ "UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">";
RegisterTest( //
"GoogleTestVerification", full_name.c_str(),
nullptr, // No type parameter.
@@ -1005,42 +998,10 @@ std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
// Returns the current time in milliseconds.
TimeInMillis GetTimeInMillis() {
-#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
- // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
- // http://analogous.blogspot.com/2005/04/epoch.html
- const TimeInMillis kJavaEpochToWinFileTimeDelta =
- static_cast<TimeInMillis>(116444736UL) * 100000UL;
- const DWORD kTenthMicrosInMilliSecond = 10000;
-
- SYSTEMTIME now_systime;
- FILETIME now_filetime;
- ULARGE_INTEGER now_int64;
- GetSystemTime(&now_systime);
- if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
- now_int64.LowPart = now_filetime.dwLowDateTime;
- now_int64.HighPart = now_filetime.dwHighDateTime;
- now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
- kJavaEpochToWinFileTimeDelta;
- return now_int64.QuadPart;
- }
- return 0;
-#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
- __timeb64 now;
-
- // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
- // (deprecated function) there.
- GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
- _ftime64(&now);
- GTEST_DISABLE_MSC_DEPRECATED_POP_()
-
- return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
-#elif GTEST_HAS_GETTIMEOFDAY_
- struct timeval now;
- gettimeofday(&now, nullptr);
- return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
-#else
-# error "Don't know how to get the current time on your system."
-#endif
+ return std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::system_clock::now() -
+ std::chrono::system_clock::from_time_t(0))
+ .count();
}
// Utilities
@@ -1555,6 +1516,31 @@ AssertionResult DoubleNearPredFormat(const char* expr1,
const double diff = fabs(val1 - val2);
if (diff <= abs_error) return AssertionSuccess();
+ // Find the value which is closest to zero.
+ const double min_abs = std::min(fabs(val1), fabs(val2));
+ // Find the distance to the next double from that value.
+ const double epsilon =
+ nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
+ // Detect the case where abs_error is so small that EXPECT_NEAR is
+ // effectively the same as EXPECT_EQUAL, and give an informative error
+ // message so that the situation can be more easily understood without
+ // requiring exotic floating-point knowledge.
+ // Don't do an epsilon check if abs_error is zero because that implies
+ // that an equality check was actually intended.
+ if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
+ abs_error < epsilon) {
+ return AssertionFailure()
+ << "The difference between " << expr1 << " and " << expr2 << " is "
+ << diff << ", where\n"
+ << expr1 << " evaluates to " << val1 << ",\n"
+ << expr2 << " evaluates to " << val2 << ".\nThe abs_error parameter "
+ << abs_error_expr << " evaluates to " << abs_error
+ << " which is smaller than the minimum distance between doubles for "
+ "numbers of this magnitude which is "
+ << epsilon
+ << ", thus making this EXPECT_NEAR check equivalent to "
+ "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
+ }
return AssertionFailure()
<< "The difference between " << expr1 << " and " << expr2
<< " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
@@ -2141,8 +2127,13 @@ bool String::EndsWithCaseInsensitive(
// Formats an int value as "%02d".
std::string String::FormatIntWidth2(int value) {
+ return FormatIntWidthN(value, 2);
+}
+
+// Formats an int value to given width with leading zeros.
+std::string String::FormatIntWidthN(int value, int width) {
std::stringstream ss;
- ss << std::setfill('0') << std::setw(2) << value;
+ ss << std::setfill('0') << std::setw(width) << value;
return ss.str();
}
@@ -3007,9 +2998,9 @@ void TestSuite::Run() {
// Call both legacy and the new API
repeater->OnTestSuiteStart(*this);
// Legacy API is deprecated but still available
-#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
repeater->OnTestCaseStart(*this);
-#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
@@ -3034,9 +3025,9 @@ void TestSuite::Run() {
// Call both legacy and the new API
repeater->OnTestSuiteEnd(*this);
// Legacy API is deprecated but still available
-#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
repeater->OnTestCaseEnd(*this);
-#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
impl->set_current_test_suite(nullptr);
}
@@ -3053,9 +3044,9 @@ void TestSuite::Skip() {
// Call both legacy and the new API
repeater->OnTestSuiteStart(*this);
// Legacy API is deprecated but still available
-#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
repeater->OnTestCaseStart(*this);
-#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
for (int i = 0; i < total_test_count(); i++) {
GetMutableTestInfo(i)->Skip();
@@ -3064,9 +3055,9 @@ void TestSuite::Skip() {
// Call both legacy and the new API
repeater->OnTestSuiteEnd(*this);
// Legacy API is deprecated but still available
-#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
repeater->OnTestCaseEnd(*this);
-#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
impl->set_current_test_suite(nullptr);
}
@@ -3277,7 +3268,7 @@ bool ShouldUseColor(bool stdout_is_tty) {
// This routine must actually emit the characters rather than return a string
// that would be colored when printed, as can be done on Linux.
-void ColoredPrintf(GTestColor color, const char* fmt, ...) {
+static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
@@ -4101,13 +4092,14 @@ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
struct tm time_struct;
if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
return "";
- // YYYY-MM-DDThh:mm:ss
+ // YYYY-MM-DDThh:mm:ss.sss
return StreamableToString(time_struct.tm_year + 1900) + "-" +
String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
String::FormatIntWidth2(time_struct.tm_mday) + "T" +
String::FormatIntWidth2(time_struct.tm_hour) + ":" +
String::FormatIntWidth2(time_struct.tm_min) + ":" +
- String::FormatIntWidth2(time_struct.tm_sec);
+ String::FormatIntWidth2(time_struct.tm_sec) + "." +
+ String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);
}
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc
index b0dda27f..c0b3d1f2 100644
--- a/googletest/test/googletest-death-test-test.cc
+++ b/googletest/test/googletest-death-test-test.cc
@@ -298,6 +298,13 @@ TEST(ExitStatusPredicateTest, KilledBySignal) {
# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
// Tests that the death test macros expand to code which may or may not
// be followed by operator<<, and that in either case the complete text
// comprises only a single C++ statement.
@@ -321,6 +328,9 @@ TEST_F(TestForDeathTest, SingleStatement) {
else
EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
# if GTEST_USES_PCRE
@@ -1376,7 +1386,11 @@ 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
EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I d[aeiou]e");
+#else
+ EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I di?e");
+#endif
}
TEST(MatcherDeathTest, MonomorphicMatcherMatches) {
@@ -1464,6 +1478,13 @@ TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
namespace {
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
// Tests that the death test macros expand to code which may or may not
// be followed by operator<<, and that in either case the complete text
// comprises only a single C++ statement.
@@ -1489,6 +1510,9 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
else
EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
// Tests that conditional death test macros expand to code which interacts
// well with switch statements.
diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt
index 8bc45800..3fab3b97 100644
--- a/googletest/test/googletest-output-test-golden-lin.txt
+++ b/googletest/test/googletest-output-test-golden-lin.txt
@@ -983,33 +983,42 @@ Stack trace: (omitted)
[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a"
[----------] 3 tests from GoogleTestVerification
-[ RUN ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite<NoTests>
-Paramaterized test suite NoTests is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are defined via TEST_P . No test cases will run.
+[ RUN ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<NoTests>
+googletest-output-test_.cc:#: Failure
+Parameterized test suite NoTests is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are defined via TEST_P . No test cases will run.
Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from code that always depend on code that provides TEST_P. Failing to do so is often an indication of dead code, e.g. the last TEST_P was removed but the rest got left behind.
To suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NoTests);
-[ OK ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite<NoTests>
-[ RUN ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite<DetectNotInstantiatedTest>
-Paramaterized test suite DetectNotInstantiatedTest is defined via TEST_P, but never instantiated. None of the test cases will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only ones provided expand to nothing.
+Stack trace: (omitted)
+
+[ FAILED ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<NoTests>
+[ RUN ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<DetectNotInstantiatedTest>
+googletest-output-test_.cc:#: Failure
+Parameterized test suite DetectNotInstantiatedTest is defined via TEST_P, but never instantiated. None of the test cases will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only ones provided expand to nothing.
Ideally, TEST_P definitions should only ever be included as part of binaries that intend to use them. (As opposed to, for example, being placed in a library that may be linked in to get other utilities.)
To suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(DetectNotInstantiatedTest);
-[ OK ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite<DetectNotInstantiatedTest>
-[ RUN ] GoogleTestVerification.UninstantiatedTypeParamaterizedTestSuite<DetectNotInstantiatedTypesTest>
-Type paramaterized test suite DetectNotInstantiatedTypesTest is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run.
+Stack trace: (omitted)
+
+[ FAILED ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<DetectNotInstantiatedTest>
+[ RUN ] GoogleTestVerification.UninstantiatedTypeParameterizedTestSuite<DetectNotInstantiatedTypesTest>
+googletest-output-test_.cc:#: Failure
+Type parameterized test suite DetectNotInstantiatedTypesTest is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run.
Ideally, TYPED_TEST_P definitions should only ever be included as part of binaries that intend to use them. (As opposed to, for example, being placed in a library that may be linked in to get other utilities.)
-To suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is definedin in:
+To suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(DetectNotInstantiatedTypesTest);
-[ OK ] GoogleTestVerification.UninstantiatedTypeParamaterizedTestSuite<DetectNotInstantiatedTypesTest>
+Stack trace: (omitted)
+
+[ FAILED ] GoogleTestVerification.UninstantiatedTypeParameterizedTestSuite<DetectNotInstantiatedTypesTest>
[----------] Global test environment tear-down
BarEnvironment::TearDown() called.
googletest-output-test_.cc:#: Failure
@@ -1024,8 +1033,8 @@ Expected fatal failure.
Stack trace: (omitted)
[==========] 88 tests from 41 test suites ran.
-[ PASSED ] 34 tests.
-[ FAILED ] 54 tests, listed below:
+[ PASSED ] 31 tests.
+[ FAILED ] 57 tests, listed below:
[ FAILED ] NonfatalFailureTest.EscapesStringOperands
[ FAILED ] NonfatalFailureTest.DiffForLongStrings
[ FAILED ] FatalFailureTest.FatalFailureInSubroutine
@@ -1080,8 +1089,11 @@ Stack trace: (omitted)
[ FAILED ] BadDynamicFixture2.Derived
[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2
[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a"
+[ FAILED ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<NoTests>
+[ FAILED ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<DetectNotInstantiatedTest>
+[ FAILED ] GoogleTestVerification.UninstantiatedTypeParameterizedTestSuite<DetectNotInstantiatedTypesTest>
-54 FAILED TESTS
+57 FAILED TESTS
 YOU HAVE 1 DISABLED TEST
Note: Google Test filter = FatalFailureTest.*:LoggingTest.*
diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc
index 44b99ce5..4a87df0b 100644
--- a/googletest/test/googletest-port-test.cc
+++ b/googletest/test/googletest-port-test.cc
@@ -201,6 +201,13 @@ TEST(ImplicitCastTest, CanUseImplicitConstructor) {
EXPECT_TRUE(converted);
}
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
if (AlwaysFalse())
GTEST_CHECK_(false) << "This should never be executed; "
@@ -216,6 +223,9 @@ TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
else
GTEST_CHECK_(true) << "";
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
switch (0) {
diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc
index 05c41830..c81af371 100644
--- a/googletest/test/googletest-printers-test.cc
+++ b/googletest/test/googletest-printers-test.cc
@@ -90,6 +90,18 @@ class BiggestIntConvertible {
operator ::testing::internal::BiggestInt() const { return 42; }
};
+// A parent class with two child classes. The parent and one of the kids have
+// stream operators.
+class ParentClass {};
+class ChildClassWithStreamOperator : public ParentClass {};
+class ChildClassWithoutStreamOperator : public ParentClass {};
+static void operator<<(std::ostream& os, const ParentClass&) {
+ os << "ParentClass";
+}
+static void operator<<(std::ostream& os, const ChildClassWithStreamOperator&) {
+ os << "ChildClassWithStreamOperator";
+}
+
// A user-defined unprintable class template in the global namespace.
template <typename T>
class UnprintableTemplateInGlobal {
@@ -177,6 +189,17 @@ inline ::std::ostream& operator<<(::std::ostream& os,
return os << "StreamableTemplateInFoo: " << x.value();
}
+// A user-defined streamable type in a user namespace whose operator<< is
+// templated on the type of the output stream.
+struct TemplatedStreamableInFoo {};
+
+template <typename OutputStream>
+OutputStream& operator<<(OutputStream& os,
+ const TemplatedStreamableInFoo& /*ts*/) {
+ os << "TemplatedStreamableInFoo";
+ return os;
+}
+
// A user-defined streamable but recursivly-defined container type in
// a user namespace, it mimics therefore std::filesystem::path or
// boost::filesystem::path.
@@ -310,6 +333,20 @@ TEST(PrintCharTest, UnsignedChar) {
Print(static_cast<unsigned char>('b')));
}
+TEST(PrintCharTest, Char16) {
+ EXPECT_EQ("U+0041", Print(u'A'));
+}
+
+TEST(PrintCharTest, Char32) {
+ EXPECT_EQ("U+0041", Print(U'A'));
+}
+
+#ifdef __cpp_char8_t
+TEST(PrintCharTest, Char8) {
+ EXPECT_EQ("U+0041", Print(u8'A'));
+}
+#endif
+
// Tests printing other simple, built-in types.
// bool.
@@ -359,6 +396,20 @@ 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
+ EXPECT_EQ("U+0000",
+ Print(std::numeric_limits<char8_t>::min())); // char8_t
+ EXPECT_EQ("U+00FF",
+ Print(std::numeric_limits<char8_t>::max())); // char8_t
+#endif
+ EXPECT_EQ("U+0000",
+ Print(std::numeric_limits<char16_t>::min())); // char16_t
+ EXPECT_EQ("U+FFFF",
+ Print(std::numeric_limits<char16_t>::max())); // char16_t
+ EXPECT_EQ("U+0000",
+ Print(std::numeric_limits<char32_t>::min())); // char32_t
+ EXPECT_EQ("U+FFFFFFFF",
+ Print(std::numeric_limits<char32_t>::max())); // char32_t
}
// Size types.
@@ -485,6 +536,56 @@ TEST(PrintCharPointerTest, ConstUnsignedChar) {
EXPECT_EQ("NULL", Print(p));
}
+#ifdef __cpp_char8_t
+// char8_t*
+TEST(PrintCharPointerTest, Char8) {
+ char8_t* p = reinterpret_cast<char8_t*>(0x1234);
+ EXPECT_EQ(PrintPointer(p), Print(p));
+ p = nullptr;
+ EXPECT_EQ("NULL", Print(p));
+}
+
+// const char8_t*
+TEST(PrintCharPointerTest, ConstChar8) {
+ const char8_t* p = reinterpret_cast<const char8_t*>(0x1234);
+ EXPECT_EQ(PrintPointer(p), Print(p));
+ p = nullptr;
+ EXPECT_EQ("NULL", Print(p));
+}
+#endif
+
+// char16_t*
+TEST(PrintCharPointerTest, Char16) {
+ char16_t* p = reinterpret_cast<char16_t*>(0x1234);
+ EXPECT_EQ(PrintPointer(p), Print(p));
+ p = nullptr;
+ EXPECT_EQ("NULL", Print(p));
+}
+
+// const char16_t*
+TEST(PrintCharPointerTest, ConstChar16) {
+ const char16_t* p = reinterpret_cast<const char16_t*>(0x1234);
+ EXPECT_EQ(PrintPointer(p), Print(p));
+ p = nullptr;
+ EXPECT_EQ("NULL", Print(p));
+}
+
+// char32_t*
+TEST(PrintCharPointerTest, Char32) {
+ char32_t* p = reinterpret_cast<char32_t*>(0x1234);
+ EXPECT_EQ(PrintPointer(p), Print(p));
+ p = nullptr;
+ EXPECT_EQ("NULL", Print(p));
+}
+
+// const char32_t*
+TEST(PrintCharPointerTest, ConstChar32) {
+ const char32_t* p = reinterpret_cast<const char32_t*>(0x1234);
+ EXPECT_EQ(PrintPointer(p), Print(p));
+ p = nullptr;
+ EXPECT_EQ("NULL", Print(p));
+}
+
// Tests printing pointers to simple, built-in types.
// bool*.
@@ -643,6 +744,35 @@ TEST(PrintArrayTest, WConstCharArrayWithTerminatingNul) {
EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a));
}
+#ifdef __cpp_char8_t
+// char8_t array.
+TEST(PrintArrayTest, Char8Array) {
+ const char8_t a[] = u8"Hello, world!";
+ EXPECT_EQ(
+ "{ U+0048, U+0065, U+006C, U+006C, U+006F, U+002C, U+0020, U+0077, "
+ "U+006F, U+0072, U+006C, U+0064, U+0021, U+0000 }",
+ PrintArrayHelper(a));
+}
+#endif
+
+// char16_t array.
+TEST(PrintArrayTest, Char16Array) {
+ const char16_t a[] = u"Hello, 世界";
+ EXPECT_EQ(
+ "{ U+0048, U+0065, U+006C, U+006C, U+006F, U+002C, U+0020, U+4E16, "
+ "U+754C, U+0000 }",
+ PrintArrayHelper(a));
+}
+
+// char32_t array.
+TEST(PrintArrayTest, Char32Array) {
+ const char32_t a[] = U"Hello, 世界";
+ EXPECT_EQ(
+ "{ U+0048, U+0065, U+006C, U+006C, U+006F, U+002C, U+0020, U+4E16, "
+ "U+754C, U+0000 }",
+ PrintArrayHelper(a));
+}
+
// Array of objects.
TEST(PrintArrayTest, ObjectArray) {
std::string a[3] = {"Hi", "Hello", "Ni hao"};
@@ -702,6 +832,35 @@ TEST(PrintWideStringTest, StringAmbiguousHex) {
}
#endif // GTEST_HAS_STD_WSTRING
+#ifdef __cpp_char8_t
+TEST(PrintStringTest, U8String) {
+ std::u8string str = u8"Hello, world!";
+ EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
+ EXPECT_EQ(
+ "{ U+0048, U+0065, U+006C, U+006C, U+006F, U+002C, U+0020, U+0077, "
+ "U+006F, U+0072, U+006C, U+0064, U+0021 }",
+ Print(str));
+}
+#endif
+
+TEST(PrintStringTest, U16String) {
+ std::u16string str = u"Hello, 世界";
+ EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
+ EXPECT_EQ(
+ "{ U+0048, U+0065, U+006C, U+006C, U+006F, U+002C, U+0020, U+4E16, "
+ "U+754C }",
+ Print(str));
+}
+
+TEST(PrintStringTest, U32String) {
+ std::u32string str = U"Hello, 世界";
+ EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
+ EXPECT_EQ(
+ "{ U+0048, U+0065, U+006C, U+006C, U+006F, U+002C, U+0020, U+4E16, "
+ "U+754C }",
+ Print(str));
+}
+
// Tests printing types that support generic streaming (i.e. streaming
// to std::basic_ostream<Char, CharTraits> for any valid Char and
// CharTraits types).
@@ -1065,6 +1224,20 @@ TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
Print(::foo::StreamableTemplateInFoo<int>()));
}
+TEST(PrintStreamableTypeTest, TypeInUserNamespaceWithTemplatedStreamOperator) {
+ EXPECT_EQ("TemplatedStreamableInFoo",
+ Print(::foo::TemplatedStreamableInFoo()));
+}
+
+TEST(PrintStreamableTypeTest, SubclassUsesSuperclassStreamOperator) {
+ ParentClass parent;
+ ChildClassWithStreamOperator child_stream;
+ ChildClassWithoutStreamOperator child_no_stream;
+ EXPECT_EQ("ParentClass", Print(parent));
+ EXPECT_EQ("ChildClassWithStreamOperator", Print(child_stream));
+ EXPECT_EQ("ParentClass", Print(child_no_stream));
+}
+
// Tests printing a user-defined recursive container type that has a <<
// operator.
TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
diff --git a/googletest/test/googletest-shuffle-test_.cc b/googletest/test/googletest-shuffle-test_.cc
index c1fc1066..4505663a 100644
--- a/googletest/test/googletest-shuffle-test_.cc
+++ b/googletest/test/googletest-shuffle-test_.cc
@@ -82,7 +82,7 @@ class TestNamePrinter : public EmptyTestEventListener {
}
void OnTestStart(const TestInfo& test_info) override {
- printf("%s.%s\n", test_info.test_case_name(), test_info.name());
+ printf("%s.%s\n", test_info.test_suite_name(), test_info.name());
}
};
diff --git a/googletest/test/gtest-typed-test_test.cc b/googletest/test/gtest-typed-test_test.cc
index 0c1f660f..de1db0cb 100644
--- a/googletest/test/gtest-typed-test_test.cc
+++ b/googletest/test/gtest-typed-test_test.cc
@@ -193,13 +193,13 @@ TYPED_TEST(TypedTestWithNames, TestSuiteName) {
if (std::is_same<TypeParam, char>::value) {
EXPECT_STREQ(::testing::UnitTest::GetInstance()
->current_test_info()
- ->test_case_name(),
+ ->test_suite_name(),
"TypedTestWithNames/char0");
}
if (std::is_same<TypeParam, int>::value) {
EXPECT_STREQ(::testing::UnitTest::GetInstance()
->current_test_info()
- ->test_case_name(),
+ ->test_suite_name(),
"TypedTestWithNames/int1");
}
}
@@ -315,13 +315,13 @@ TYPED_TEST_P(TypeParametrizedTestWithNames, TestSuiteName) {
if (std::is_same<TypeParam, char>::value) {
EXPECT_STREQ(::testing::UnitTest::GetInstance()
->current_test_info()
- ->test_case_name(),
+ ->test_suite_name(),
"CustomName/TypeParametrizedTestWithNames/parChar0");
}
if (std::is_same<TypeParam, int>::value) {
EXPECT_STREQ(::testing::UnitTest::GetInstance()
->current_test_info()
- ->test_case_name(),
+ ->test_suite_name(),
"CustomName/TypeParametrizedTestWithNames/parInt1");
}
}
diff --git a/googletest/test/gtest_list_output_unittest.py b/googletest/test/gtest_list_output_unittest.py
index 3bba7ea2..b882126e 100644
--- a/googletest/test/gtest_list_output_unittest.py
+++ b/googletest/test/gtest_list_output_unittest.py
@@ -46,16 +46,42 @@ GTEST_LIST_TESTS_FLAG = '--gtest_list_tests'
GTEST_OUTPUT_FLAG = '--gtest_output'
EXPECTED_XML = """<\?xml version="1.0" encoding="UTF-8"\?>
-<testsuites tests="2" name="AllTests">
+<testsuites tests="16" name="AllTests">
<testsuite name="FooTest" tests="2">
<testcase name="Test1" file=".*gtest_list_output_unittest_.cc" line="43" />
<testcase name="Test2" file=".*gtest_list_output_unittest_.cc" line="45" />
</testsuite>
+ <testsuite name="FooTestFixture" tests="2">
+ <testcase name="Test3" file=".*gtest_list_output_unittest_.cc" line="48" />
+ <testcase name="Test4" file=".*gtest_list_output_unittest_.cc" line="49" />
+ </testsuite>
+ <testsuite name="TypedTest/0" tests="2">
+ <testcase name="Test7" type_param="int" file=".*gtest_list_output_unittest_.cc" line="61" />
+ <testcase name="Test8" type_param="int" file=".*gtest_list_output_unittest_.cc" line="62" />
+ </testsuite>
+ <testsuite name="TypedTest/1" tests="2">
+ <testcase name="Test7" type_param="bool" file=".*gtest_list_output_unittest_.cc" line="61" />
+ <testcase name="Test8" type_param="bool" file=".*gtest_list_output_unittest_.cc" line="62" />
+ </testsuite>
+ <testsuite name="Single/TypeParameterizedTestSuite/0" tests="2">
+ <testcase name="Test9" type_param="int" file=".*gtest_list_output_unittest_.cc" line="69" />
+ <testcase name="Test10" type_param="int" file=".*gtest_list_output_unittest_.cc" line="70" />
+ </testsuite>
+ <testsuite name="Single/TypeParameterizedTestSuite/1" tests="2">
+ <testcase name="Test9" type_param="bool" file=".*gtest_list_output_unittest_.cc" line="69" />
+ <testcase name="Test10" type_param="bool" file=".*gtest_list_output_unittest_.cc" line="70" />
+ </testsuite>
+ <testsuite name="ValueParam/ValueParamTest" tests="4">
+ <testcase name="Test5/0" value_param="33" file=".*gtest_list_output_unittest_.cc" line="52" />
+ <testcase name="Test5/1" value_param="42" file=".*gtest_list_output_unittest_.cc" line="52" />
+ <testcase name="Test6/0" value_param="33" file=".*gtest_list_output_unittest_.cc" line="53" />
+ <testcase name="Test6/1" value_param="42" file=".*gtest_list_output_unittest_.cc" line="53" />
+ </testsuite>
</testsuites>
"""
EXPECTED_JSON = """{
- "tests": 2,
+ "tests": 16,
"name": "AllTests",
"testsuites": \[
{
@@ -73,6 +99,124 @@ EXPECTED_JSON = """{
"line": 45
}
\]
+ },
+ {
+ "name": "FooTestFixture",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test3",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 48
+ },
+ {
+ "name": "Test4",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 49
+ }
+ \]
+ },
+ {
+ "name": "TypedTest\\\\/0",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test7",
+ "type_param": "int",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 61
+ },
+ {
+ "name": "Test8",
+ "type_param": "int",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 62
+ }
+ \]
+ },
+ {
+ "name": "TypedTest\\\\/1",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test7",
+ "type_param": "bool",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 61
+ },
+ {
+ "name": "Test8",
+ "type_param": "bool",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 62
+ }
+ \]
+ },
+ {
+ "name": "Single\\\\/TypeParameterizedTestSuite\\\\/0",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test9",
+ "type_param": "int",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 69
+ },
+ {
+ "name": "Test10",
+ "type_param": "int",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 70
+ }
+ \]
+ },
+ {
+ "name": "Single\\\\/TypeParameterizedTestSuite\\\\/1",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test9",
+ "type_param": "bool",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 69
+ },
+ {
+ "name": "Test10",
+ "type_param": "bool",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 70
+ }
+ \]
+ },
+ {
+ "name": "ValueParam\\\\/ValueParamTest",
+ "tests": 4,
+ "testsuite": \[
+ {
+ "name": "Test5\\\\/0",
+ "value_param": "33",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 52
+ },
+ {
+ "name": "Test5\\\\/1",
+ "value_param": "42",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 52
+ },
+ {
+ "name": "Test6\\\\/0",
+ "value_param": "33",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 53
+ },
+ {
+ "name": "Test6\\\\/1",
+ "value_param": "42",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 53
+ }
+ \]
}
\]
}
@@ -114,8 +258,9 @@ class GTestListTestsOutputUnitTest(gtest_test_utils.TestCase):
p = gtest_test_utils.Subprocess(
command, env=environ_copy, working_dir=gtest_test_utils.GetTempDir())
- self.assert_(p.exited)
- self.assertEquals(0, p.exit_code)
+ self.assertTrue(p.exited)
+ self.assertEqual(0, p.exit_code)
+ self.assertTrue(os.path.isfile(file_path))
with open(file_path) as f:
result = f.read()
return result
@@ -128,7 +273,7 @@ class GTestListTestsOutputUnitTest(gtest_test_utils.TestCase):
for actual_line in actual_lines:
expected_line = expected_lines[line_count]
expected_line_re = re.compile(expected_line.strip())
- self.assert_(
+ self.assertTrue(
expected_line_re.match(actual_line.strip()),
('actual output of "%s",\n'
'which does not match expected regex of "%s"\n'
diff --git a/googletest/test/gtest_list_output_unittest_.cc b/googletest/test/gtest_list_output_unittest_.cc
index b1c7b4de..2eea3ebd 100644
--- a/googletest/test/gtest_list_output_unittest_.cc
+++ b/googletest/test/gtest_list_output_unittest_.cc
@@ -44,6 +44,36 @@ TEST(FooTest, Test1) {}
TEST(FooTest, Test2) {}
+class FooTestFixture : public ::testing::Test {};
+TEST_F(FooTestFixture, Test3) {}
+TEST_F(FooTestFixture, Test4) {}
+
+class ValueParamTest : public ::testing::TestWithParam<int> {};
+TEST_P(ValueParamTest, Test5) {}
+TEST_P(ValueParamTest, Test6) {}
+INSTANTIATE_TEST_SUITE_P(ValueParam, ValueParamTest, ::testing::Values(33, 42));
+
+#if GTEST_HAS_TYPED_TEST
+template <typename T>
+class TypedTest : public ::testing::Test {};
+typedef testing::Types<int, bool> TypedTestTypes;
+TYPED_TEST_SUITE(TypedTest, TypedTestTypes);
+TYPED_TEST(TypedTest, Test7) {}
+TYPED_TEST(TypedTest, Test8) {}
+#endif
+
+#if GTEST_HAS_TYPED_TEST_P
+template <typename T>
+class TypeParameterizedTestSuite : public ::testing::Test {};
+TYPED_TEST_SUITE_P(TypeParameterizedTestSuite);
+TYPED_TEST_P(TypeParameterizedTestSuite, Test9) {}
+TYPED_TEST_P(TypeParameterizedTestSuite, Test10) {}
+REGISTER_TYPED_TEST_SUITE_P(TypeParameterizedTestSuite, Test9, Test10);
+typedef testing::Types<int, bool> TypeParameterizedTestSuiteTypes; // NOLINT
+INSTANTIATE_TYPED_TEST_SUITE_P(Single, TypeParameterizedTestSuite,
+ TypeParameterizedTestSuiteTypes);
+#endif
+
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc
index a6d44abd..56bfa8c5 100644
--- a/googletest/test/gtest_unittest.cc
+++ b/googletest/test/gtest_unittest.cc
@@ -64,6 +64,7 @@ TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
#include <cstdint>
#include <map>
#include <ostream>
+#include <string>
#include <type_traits>
#include <unordered_set>
#include <vector>
@@ -218,17 +219,18 @@ using testing::GTEST_FLAG(stream_result_to);
using testing::GTEST_FLAG(throw_on_failure);
using testing::IsNotSubstring;
using testing::IsSubstring;
+using testing::kMaxStackTraceDepth;
using testing::Message;
using testing::ScopedFakeTestPartResultReporter;
using testing::StaticAssertTypeEq;
using testing::Test;
-using testing::TestCase;
using testing::TestEventListeners;
using testing::TestInfo;
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;
@@ -244,7 +246,6 @@ using testing::internal::FloatingPoint;
using testing::internal::ForEach;
using testing::internal::FormatEpochTimeInMillisAsIso8601;
using testing::internal::FormatTimeInMillisAsSeconds;
-using testing::internal::GTestFlagSaver;
using testing::internal::GetCurrentOsStackTraceExceptTop;
using testing::internal::GetElementOr;
using testing::internal::GetNextRandomSeed;
@@ -253,11 +254,14 @@ using testing::internal::GetTestTypeId;
using testing::internal::GetTimeInMillis;
using testing::internal::GetTypeId;
using testing::internal::GetUnitTestImpl;
+using testing::internal::GTestFlagSaver;
+using testing::internal::HasDebugStringAndShortDebugString;
using testing::internal::Int32FromEnvOrDie;
-using testing::internal::IsAProtocolMessage;
using testing::internal::IsContainer;
using testing::internal::IsContainerTest;
using testing::internal::IsNotContainer;
+using testing::internal::kMaxRandomSeed;
+using testing::internal::kTestTypeIdInGoogleTest;
using testing::internal::NativeArray;
using testing::internal::OsStackTraceGetter;
using testing::internal::OsStackTraceGetterInterface;
@@ -279,9 +283,6 @@ using testing::internal::WideStringToUtf8;
using testing::internal::edit_distance::CalculateOptimalEdits;
using testing::internal::edit_distance::CreateUnifiedDiff;
using testing::internal::edit_distance::EditType;
-using testing::internal::kMaxRandomSeed;
-using testing::internal::kTestTypeIdInGoogleTest;
-using testing::kMaxStackTraceDepth;
#if GTEST_HAS_STREAM_REDIRECTION
using testing::internal::CaptureStdout;
@@ -485,28 +486,28 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
- EXPECT_EQ("2011-10-31T18:52:42",
+ EXPECT_EQ("2011-10-31T18:52:42.000",
FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
}
-TEST_F(FormatEpochTimeInMillisAsIso8601Test, MillisecondsDoNotAffectResult) {
+TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
EXPECT_EQ(
- "2011-10-31T18:52:42",
+ "2011-10-31T18:52:42.234",
FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
- EXPECT_EQ("2011-09-03T05:07:02",
+ EXPECT_EQ("2011-09-03T05:07:02.000",
FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
- EXPECT_EQ("2011-09-28T17:08:22",
+ EXPECT_EQ("2011-09-28T17:08:22.000",
FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
- EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0));
+ EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0));
}
# ifdef __BORLANDC__
@@ -2767,7 +2768,7 @@ class FloatingPointTest : public Test {
typedef typename Floating::Bits Bits;
void SetUp() override {
- const size_t max_ulps = Floating::kMaxUlps;
+ const uint32_t max_ulps = Floating::kMaxUlps;
// The bits that represent 0.0.
const Bits zero_bits = Floating(0).bits();
@@ -3084,6 +3085,13 @@ TEST_F(DoubleTest, EXPECT_NEAR) {
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
"The difference between 1.0 and 1.5 is 0.5, "
"which exceeds 0.25");
+ // At this magnitude adjacent doubles are 512.0 apart, so this triggers a
+ // slightly different failure reporting path.
+ EXPECT_NONFATAL_FAILURE(
+ EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0),
+ "The abs_error parameter 1.0 evaluates to 1 which is smaller than the "
+ "minimum distance between doubles for numbers of this magnitude which is "
+ "512");
}
// Tests ASSERT_NEAR.
@@ -3345,6 +3353,16 @@ TEST_F(SingleEvaluationTest, OtherCases) {
#if GTEST_HAS_EXCEPTIONS
+#if GTEST_HAS_RTTI
+
+#define ERROR_DESC "std::runtime_error"
+
+#else // GTEST_HAS_RTTI
+
+#define ERROR_DESC "an std::exception-derived error"
+
+#endif // GTEST_HAS_RTTI
+
void ThrowAnInteger() {
throw 1;
}
@@ -3368,31 +3386,38 @@ TEST_F(SingleEvaluationTest, ExceptionTests) {
}, bool), "throws a different type");
EXPECT_EQ(2, a_);
+ // failed EXPECT_THROW, throws runtime error
+ EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
+ a_++;
+ ThrowRuntimeError("A description");
+ }, bool), "throws " ERROR_DESC " with description \"A description\"");
+ EXPECT_EQ(3, a_);
+
// failed EXPECT_THROW, throws nothing
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
- EXPECT_EQ(3, a_);
+ EXPECT_EQ(4, a_);
// successful EXPECT_NO_THROW
EXPECT_NO_THROW(a_++);
- EXPECT_EQ(4, a_);
+ EXPECT_EQ(5, a_);
// failed EXPECT_NO_THROW
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
a_++;
ThrowAnInteger();
}), "it throws");
- EXPECT_EQ(5, a_);
+ EXPECT_EQ(6, a_);
// successful EXPECT_ANY_THROW
EXPECT_ANY_THROW({ // NOLINT
a_++;
ThrowAnInteger();
});
- EXPECT_EQ(6, a_);
+ EXPECT_EQ(7, a_);
// failed EXPECT_ANY_THROW
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
- EXPECT_EQ(7, a_);
+ EXPECT_EQ(8, a_);
}
#endif // GTEST_HAS_EXCEPTIONS
@@ -3812,6 +3837,12 @@ TEST(AssertionTest, ASSERT_THROW) {
ASSERT_THROW(ThrowAnInteger(), bool),
"Expected: ThrowAnInteger() throws an exception of type bool.\n"
" Actual: it throws a different type.");
+ EXPECT_FATAL_FAILURE(
+ ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error),
+ "Expected: ThrowRuntimeError(\"A description\") "
+ "throws an exception of type std::logic_error.\n "
+ "Actual: it throws " ERROR_DESC " "
+ "with description \"A description\".");
# endif
EXPECT_FATAL_FAILURE(
@@ -3829,8 +3860,8 @@ TEST(AssertionTest, ASSERT_NO_THROW) {
EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
"Expected: ThrowRuntimeError(\"A description\") "
"doesn't throw an exception.\n "
- "Actual: it throws std::exception-derived exception "
- "with description: \"A description\".");
+ "Actual: it throws " ERROR_DESC " "
+ "with description \"A description\".");
}
// Tests ASSERT_ANY_THROW.
@@ -4100,11 +4131,13 @@ TEST(HRESULTAssertionTest, Streaming) {
#endif // GTEST_OS_WINDOWS
-#ifdef __BORLANDC__
-// Silences warnings: "Condition is always true", "Unreachable code"
-# pragma option push -w-ccc -w-rch
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
#endif
-
// Tests that the assertion macros behave like single statements.
TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
@@ -4124,6 +4157,9 @@ TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
else
EXPECT_GT(3, 2) << "";
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
#if GTEST_HAS_EXCEPTIONS
// Tests that the compiler will not complain about unreachable code in the
@@ -4140,6 +4176,17 @@ TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
}
+TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
+ EXPECT_THROW(throw std::exception(), std::exception);
+}
+
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
EXPECT_THROW(ThrowNothing(), bool);
@@ -4165,8 +4212,19 @@ TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
else
; // NOLINT
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
+
#endif // GTEST_HAS_EXCEPTIONS
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
@@ -4189,6 +4247,9 @@ TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
else
ASSERT_NO_FATAL_FAILURE(SUCCEED());
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
// Tests that the assertion macros work well with switch statements.
TEST(AssertionSyntaxTest, WorksWithSwitch) {
@@ -4550,6 +4611,12 @@ TEST(ExpectTest, EXPECT_THROW) {
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
"Expected: ThrowAnInteger() throws an exception of "
"type bool.\n Actual: it throws a different type.");
+ EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowRuntimeError("A description"),
+ std::logic_error),
+ "Expected: ThrowRuntimeError(\"A description\") "
+ "throws an exception of type std::logic_error.\n "
+ "Actual: it throws " ERROR_DESC " "
+ "with description \"A description\".");
EXPECT_NONFATAL_FAILURE(
EXPECT_THROW(ThrowNothing(), bool),
"Expected: ThrowNothing() throws an exception of type bool.\n"
@@ -4565,8 +4632,8 @@ TEST(ExpectTest, EXPECT_NO_THROW) {
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
"Expected: ThrowRuntimeError(\"A description\") "
"doesn't throw an exception.\n "
- "Actual: it throws std::exception-derived exception "
- "with description: \"A description\".");
+ "Actual: it throws " ERROR_DESC " "
+ "with description \"A description\".");
}
// Tests EXPECT_ANY_THROW.
@@ -5306,7 +5373,7 @@ class TestInfoTest : public Test {
TEST_F(TestInfoTest, Names) {
const TestInfo* const test_info = GetTestInfo("Names");
- ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
+ ASSERT_STREQ("TestInfoTest", test_info->test_suite_name());
ASSERT_STREQ("Names", test_info->name());
}
@@ -5376,7 +5443,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);
// Tests setting up and tearing down a test case.
// Legacy API is deprecated but still available
-#ifndef REMOVE_LEGACY_TEST_CASEAPI
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
class SetUpTestCaseTest : public Test {
protected:
// This will be called once before the first test in this test case
@@ -5435,7 +5502,7 @@ TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
TEST_F(SetUpTestCaseTest, Test2) {
EXPECT_STREQ("123", shared_resource_);
}
-#endif // REMOVE_LEGACY_TEST_CASEAPI
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Tests SetupTestSuite/TearDown TestSuite
class SetUpTestSuiteTest : public Test {
@@ -6341,8 +6408,8 @@ TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
UnitTest::GetInstance()->current_test_info();
ASSERT_TRUE(nullptr != test_info)
<< "There is a test running so we should have a valid TestInfo.";
- EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
- << "Expected the name of the currently running test case.";
+ EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
+ << "Expected the name of the currently running test suite.";
EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
<< "Expected the name of the currently running test.";
}
@@ -6356,8 +6423,8 @@ TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
UnitTest::GetInstance()->current_test_info();
ASSERT_TRUE(nullptr != test_info)
<< "There is a test running so we should have a valid TestInfo.";
- EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
- << "Expected the name of the currently running test case.";
+ EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
+ << "Expected the name of the currently running test suite.";
EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
<< "Expected the name of the currently running test.";
}
@@ -7145,24 +7212,71 @@ GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
class ConversionHelperBase {};
class ConversionHelperDerived : public ConversionHelperBase {};
-// Tests that IsAProtocolMessage<T>::value is a compile-time constant.
-TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
- GTEST_COMPILE_ASSERT_(IsAProtocolMessage<::proto2::MessageLite>::value,
- const_true);
- GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
-}
+struct HasDebugStringMethods {
+ std::string DebugString() const { return ""; }
+ std::string ShortDebugString() const { return ""; }
+};
+
+struct InheritsDebugStringMethods : public HasDebugStringMethods {};
+
+struct WrongTypeDebugStringMethod {
+ std::string DebugString() const { return ""; }
+ int ShortDebugString() const { return 1; }
+};
-// Tests that IsAProtocolMessage<T>::value is true when T is
-// proto2::Message or a sub-class of it.
-TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
- EXPECT_TRUE(IsAProtocolMessage<::proto2::MessageLite>::value);
+struct NotConstDebugStringMethod {
+ std::string DebugString() { return ""; }
+ std::string ShortDebugString() const { return ""; }
+};
+
+struct MissingDebugStringMethod {
+ std::string DebugString() { return ""; }
+};
+
+struct IncompleteType;
+
+// Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
+// constant.
+TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
+ GTEST_COMPILE_ASSERT_(
+ HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
+ const_true);
+ GTEST_COMPILE_ASSERT_(
+ HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,
+ const_true);
+ GTEST_COMPILE_ASSERT_(HasDebugStringAndShortDebugString<
+ const InheritsDebugStringMethods>::value,
+ const_true);
+ GTEST_COMPILE_ASSERT_(
+ !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,
+ const_false);
+ GTEST_COMPILE_ASSERT_(
+ !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,
+ const_false);
+ GTEST_COMPILE_ASSERT_(
+ !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,
+ const_false);
+ GTEST_COMPILE_ASSERT_(
+ !HasDebugStringAndShortDebugString<IncompleteType>::value, const_false);
+ GTEST_COMPILE_ASSERT_(!HasDebugStringAndShortDebugString<int>::value,
+ const_false);
+}
+
+// Tests that HasDebugStringAndShortDebugString<T>::value is true when T has
+// needed methods.
+TEST(HasDebugStringAndShortDebugStringTest,
+ ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
+ EXPECT_TRUE(
+ HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value);
}
-// Tests that IsAProtocolMessage<T>::value is false when T is neither
-// ::proto2::Message nor a sub-class of it.
-TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
- EXPECT_FALSE(IsAProtocolMessage<int>::value);
- EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value);
+// Tests that HasDebugStringAndShortDebugString<T>::value is false when T
+// doesn't have needed methods.
+TEST(HasDebugStringAndShortDebugStringTest,
+ ValueIsFalseWhenTypeIsNotAProtocolMessage) {
+ EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value);
+ EXPECT_FALSE(
+ HasDebugStringAndShortDebugString<const ConversionHelperBase>::value);
}
// Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
@@ -7446,6 +7560,142 @@ TEST(FlatTuple, Basic) {
EXPECT_EQ(5.1, tuple.Get<1>());
}
+namespace {
+std::string AddIntToString(int i, const std::string& s) {
+ return s + std::to_string(i);
+}
+} // namespace
+
+TEST(FlatTuple, Apply) {
+ using testing::internal::FlatTuple;
+
+ FlatTuple<int, std::string> tuple{5, "Hello"};
+
+ // Lambda.
+ EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool {
+ return i == static_cast<int>(s.size());
+ }));
+
+ // Function.
+ EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5");
+
+ // Mutating operations.
+ tuple.Apply([](int& i, std::string& s) {
+ ++i;
+ s += s;
+ });
+ EXPECT_EQ(tuple.Get<0>(), 6);
+ EXPECT_EQ(tuple.Get<1>(), "HelloHello");
+}
+
+struct ConstructionCounting {
+ ConstructionCounting() { ++default_ctor_calls; }
+ ~ConstructionCounting() { ++dtor_calls; }
+ ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; }
+ ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; }
+ ConstructionCounting& operator=(const ConstructionCounting&) {
+ ++copy_assignment_calls;
+ return *this;
+ }
+ ConstructionCounting& operator=(ConstructionCounting&&) noexcept {
+ ++move_assignment_calls;
+ return *this;
+ }
+
+ static void Reset() {
+ default_ctor_calls = 0;
+ dtor_calls = 0;
+ copy_ctor_calls = 0;
+ move_ctor_calls = 0;
+ copy_assignment_calls = 0;
+ move_assignment_calls = 0;
+ }
+
+ static int default_ctor_calls;
+ static int dtor_calls;
+ static int copy_ctor_calls;
+ static int move_ctor_calls;
+ static int copy_assignment_calls;
+ static int move_assignment_calls;
+};
+
+int ConstructionCounting::default_ctor_calls = 0;
+int ConstructionCounting::dtor_calls = 0;
+int ConstructionCounting::copy_ctor_calls = 0;
+int ConstructionCounting::move_ctor_calls = 0;
+int ConstructionCounting::copy_assignment_calls = 0;
+int ConstructionCounting::move_assignment_calls = 0;
+
+TEST(FlatTuple, ConstructorCalls) {
+ using testing::internal::FlatTuple;
+
+ // Default construction.
+ ConstructionCounting::Reset();
+ { FlatTuple<ConstructionCounting> tuple; }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
+
+ // Copy construction.
+ ConstructionCounting::Reset();
+ {
+ ConstructionCounting elem;
+ FlatTuple<ConstructionCounting> tuple{elem};
+ }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
+
+ // Move construction.
+ ConstructionCounting::Reset();
+ { FlatTuple<ConstructionCounting> tuple{ConstructionCounting{}}; }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
+
+ // Copy assignment.
+ // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
+ // elements
+ ConstructionCounting::Reset();
+ {
+ FlatTuple<ConstructionCounting> tuple;
+ ConstructionCounting elem;
+ tuple.Get<0>() = elem;
+ }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
+
+ // Move assignment.
+ // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
+ // elements
+ ConstructionCounting::Reset();
+ {
+ FlatTuple<ConstructionCounting> tuple;
+ tuple.Get<0>() = ConstructionCounting{};
+ }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1);
+
+ ConstructionCounting::Reset();
+}
+
TEST(FlatTuple, ManyTypes) {
using testing::internal::FlatTuple;
diff --git a/googletest/test/gtest_xml_test_utils.py b/googletest/test/gtest_xml_test_utils.py
index cae0bc0b..5dd0eb92 100755
--- a/googletest/test/gtest_xml_test_utils.py
+++ b/googletest/test/gtest_xml_test_utils.py
@@ -172,7 +172,7 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
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$',
+ 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')
OpenPOWER on IntegriCloud