summaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
authorSebastian Huber <sebastian.huber@embedded-brains.de>2016-12-16 13:20:29 +0100
committerSebastian Huber <sebastian.huber@embedded-brains.de>2016-12-16 13:20:29 +0100
commit0a89edfda900b6322d0823a56f3d8241c90035a2 (patch)
treeb9004a4e5ffa785f9b0bbcc9e27639e1f0d13259 /test
parent42bfaf23fb67270261942ce8f6a0e9bc0416bf33 (diff)
Google C++ Testing Framework 1.8.0
Diffstat (limited to 'test')
-rw-r--r--test/gtest-death-test_test.cc166
-rw-r--r--test/gtest-filepath_test.cc18
-rw-r--r--test/gtest-listener_test.cc11
-rw-r--r--test/gtest-param-test_test.cc157
-rw-r--r--test/gtest-port_test.cc207
-rw-r--r--test/gtest-printers_test.cc221
-rw-r--r--test/gtest-typed-test_test.cc22
-rw-r--r--test/gtest-unittest-api_test.cc4
-rwxr-xr-xtest/gtest_env_var_test.py18
-rwxr-xr-xtest/gtest_filter_unittest.py13
-rwxr-xr-xtest/gtest_list_tests_unittest.py4
-rwxr-xr-xtest/gtest_output_test.py21
-rw-r--r--test/gtest_output_test_.cc46
-rw-r--r--test/gtest_output_test_golden_lin.txt137
-rw-r--r--test/gtest_premature_exit_test.cc14
-rwxr-xr-xtest/gtest_test_utils.py8
-rwxr-xr-xtest/gtest_throw_on_failure_test.py2
-rwxr-xr-xtest/gtest_uninitialized_test.py4
-rw-r--r--test/gtest_unittest.cc433
-rwxr-xr-xtest/gtest_xml_output_unittest.py21
-rwxr-xr-xtest/gtest_xml_test_utils.py2
21 files changed, 1107 insertions, 422 deletions
diff --git a/test/gtest-death-test_test.cc b/test/gtest-death-test_test.cc
index c2d26df..bb4a3d1 100644
--- a/test/gtest-death-test_test.cc
+++ b/test/gtest-death-test_test.cc
@@ -326,12 +326,9 @@ TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
// Tests that death test macros expand to code which interacts well with switch
// statements.
TEST_F(TestForDeathTest, SwitchStatement) {
-// Microsoft compiler usually complains about switch statements without
-// case labels. We suppress that warning for this test.
-# ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable: 4065)
-# endif // _MSC_VER
+ // Microsoft compiler usually complains about switch statements without
+ // case labels. We suppress that warning for this test.
+ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
switch (0)
default:
@@ -341,9 +338,7 @@ TEST_F(TestForDeathTest, SwitchStatement) {
case 0:
EXPECT_DEATH(_exit(1), "") << "exit in switch case";
-# ifdef _MSC_VER
-# pragma warning(pop)
-# endif // _MSC_VER
+ GTEST_DISABLE_MSC_WARNINGS_POP_()
}
// Tests that a static member function can be used in a "fast" style
@@ -515,8 +510,12 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
# endif // GTEST_HAS_GLOBAL_STRING
+# if !GTEST_USES_PCRE
+
const ::std::string regex_std_str(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex_std_str);
+
+# endif // !GTEST_USES_PCRE
}
// Tests that a non-void function can be used in a death test.
@@ -699,7 +698,10 @@ TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
void AssertDebugDeathHelper(bool* aborted) {
*aborted = true;
- ASSERT_DEBUG_DEATH(return, "") << "This is expected to fail.";
+ GTEST_LOG_(INFO) << "Before ASSERT_DEBUG_DEATH";
+ ASSERT_DEBUG_DEATH(GTEST_LOG_(INFO) << "In ASSERT_DEBUG_DEATH"; return, "")
+ << "This is expected to fail.";
+ GTEST_LOG_(INFO) << "After ASSERT_DEBUG_DEATH";
*aborted = false;
}
@@ -712,6 +714,69 @@ TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
EXPECT_TRUE(aborted);
}
+TEST_F(TestForDeathTest, AssertDebugDeathAborts2) {
+ static bool aborted;
+ aborted = false;
+ EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
+ EXPECT_TRUE(aborted);
+}
+
+TEST_F(TestForDeathTest, AssertDebugDeathAborts3) {
+ static bool aborted;
+ aborted = false;
+ EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
+ EXPECT_TRUE(aborted);
+}
+
+TEST_F(TestForDeathTest, AssertDebugDeathAborts4) {
+ static bool aborted;
+ aborted = false;
+ EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
+ EXPECT_TRUE(aborted);
+}
+
+TEST_F(TestForDeathTest, AssertDebugDeathAborts5) {
+ static bool aborted;
+ aborted = false;
+ EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
+ EXPECT_TRUE(aborted);
+}
+
+TEST_F(TestForDeathTest, AssertDebugDeathAborts6) {
+ static bool aborted;
+ aborted = false;
+ EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
+ EXPECT_TRUE(aborted);
+}
+
+TEST_F(TestForDeathTest, AssertDebugDeathAborts7) {
+ static bool aborted;
+ aborted = false;
+ EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
+ EXPECT_TRUE(aborted);
+}
+
+TEST_F(TestForDeathTest, AssertDebugDeathAborts8) {
+ static bool aborted;
+ aborted = false;
+ EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
+ EXPECT_TRUE(aborted);
+}
+
+TEST_F(TestForDeathTest, AssertDebugDeathAborts9) {
+ static bool aborted;
+ aborted = false;
+ EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
+ EXPECT_TRUE(aborted);
+}
+
+TEST_F(TestForDeathTest, AssertDebugDeathAborts10) {
+ static bool aborted;
+ aborted = false;
+ EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
+ EXPECT_TRUE(aborted);
+}
+
# endif // _NDEBUG
// Tests the *_EXIT family of macros, using a variety of predicates.
@@ -826,9 +891,9 @@ class MockDeathTestFactory : public DeathTestFactory {
// Accessors.
int AssumeRoleCalls() const { return assume_role_calls_; }
int WaitCalls() const { return wait_calls_; }
- int PassedCalls() const { return passed_args_.size(); }
+ size_t PassedCalls() const { return passed_args_.size(); }
bool PassedArgument(int n) const { return passed_args_[n]; }
- int AbortCalls() const { return abort_args_.size(); }
+ size_t AbortCalls() const { return abort_args_.size(); }
DeathTest::AbortReason AbortArgument(int n) const {
return abort_args_[n];
}
@@ -989,8 +1054,8 @@ TEST_F(MacroLogicDeathTest, NothingHappens) {
EXPECT_FALSE(flag);
EXPECT_EQ(0, factory_->AssumeRoleCalls());
EXPECT_EQ(0, factory_->WaitCalls());
- EXPECT_EQ(0, factory_->PassedCalls());
- EXPECT_EQ(0, factory_->AbortCalls());
+ EXPECT_EQ(0U, factory_->PassedCalls());
+ EXPECT_EQ(0U, factory_->AbortCalls());
EXPECT_FALSE(factory_->TestDeleted());
}
@@ -1004,9 +1069,9 @@ TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
EXPECT_FALSE(flag);
EXPECT_EQ(1, factory_->AssumeRoleCalls());
EXPECT_EQ(1, factory_->WaitCalls());
- ASSERT_EQ(1, factory_->PassedCalls());
+ ASSERT_EQ(1U, factory_->PassedCalls());
EXPECT_FALSE(factory_->PassedArgument(0));
- EXPECT_EQ(0, factory_->AbortCalls());
+ EXPECT_EQ(0U, factory_->AbortCalls());
EXPECT_TRUE(factory_->TestDeleted());
}
@@ -1019,9 +1084,9 @@ TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
EXPECT_FALSE(flag);
EXPECT_EQ(1, factory_->AssumeRoleCalls());
EXPECT_EQ(1, factory_->WaitCalls());
- ASSERT_EQ(1, factory_->PassedCalls());
+ ASSERT_EQ(1U, factory_->PassedCalls());
EXPECT_TRUE(factory_->PassedArgument(0));
- EXPECT_EQ(0, factory_->AbortCalls());
+ EXPECT_EQ(0U, factory_->AbortCalls());
EXPECT_TRUE(factory_->TestDeleted());
}
@@ -1035,8 +1100,8 @@ TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
EXPECT_TRUE(flag);
EXPECT_EQ(1, factory_->AssumeRoleCalls());
EXPECT_EQ(0, factory_->WaitCalls());
- EXPECT_EQ(0, factory_->PassedCalls());
- EXPECT_EQ(1, factory_->AbortCalls());
+ EXPECT_EQ(0U, factory_->PassedCalls());
+ EXPECT_EQ(1U, factory_->AbortCalls());
EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
factory_->AbortArgument(0));
EXPECT_TRUE(factory_->TestDeleted());
@@ -1051,13 +1116,13 @@ TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
EXPECT_TRUE(flag);
EXPECT_EQ(1, factory_->AssumeRoleCalls());
EXPECT_EQ(0, factory_->WaitCalls());
- EXPECT_EQ(0, factory_->PassedCalls());
+ EXPECT_EQ(0U, factory_->PassedCalls());
// This time there are two calls to Abort: one since the test didn't
// die, and another from the ReturnSentinel when it's destroyed. The
// sentinel normally isn't destroyed if a test doesn't die, since
// _exit(2) is called in that case by ForkingDeathTest, but not by
// our MockDeathTest.
- ASSERT_EQ(2, factory_->AbortCalls());
+ ASSERT_EQ(2U, factory_->AbortCalls());
EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
factory_->AbortArgument(0));
EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
@@ -1238,7 +1303,27 @@ TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), "");
}
-#else
+TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
+ testing::GTEST_FLAG(death_test_style) = "fast";
+ EXPECT_FALSE(InDeathTestChild());
+ EXPECT_DEATH({
+ fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
+ fflush(stderr);
+ _exit(1);
+ }, "Inside");
+}
+
+TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
+ testing::GTEST_FLAG(death_test_style) = "threadsafe";
+ EXPECT_FALSE(InDeathTestChild());
+ EXPECT_DEATH({
+ fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
+ fflush(stderr);
+ _exit(1);
+ }, "Inside");
+}
+
+#else // !GTEST_HAS_DEATH_TEST follows
using testing::internal::CaptureStderr;
using testing::internal::GetCapturedStderr;
@@ -1288,27 +1373,7 @@ TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
EXPECT_EQ(1, n);
}
-TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
- testing::GTEST_FLAG(death_test_style) = "fast";
- EXPECT_FALSE(InDeathTestChild());
- EXPECT_DEATH({
- fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
- fflush(stderr);
- _exit(1);
- }, "Inside");
-}
-
-TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
- testing::GTEST_FLAG(death_test_style) = "threadsafe";
- EXPECT_FALSE(InDeathTestChild());
- EXPECT_DEATH({
- fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
- fflush(stderr);
- _exit(1);
- }, "Inside");
-}
-
-#endif // GTEST_HAS_DEATH_TEST
+#endif // !GTEST_HAS_DEATH_TEST
// Tests that the death test macros expand to code which may or may not
// be followed by operator<<, and that in either case the complete text
@@ -1339,12 +1404,9 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
// Tests that conditional death test macros expand to code which interacts
// well with switch statements.
TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
-// Microsoft compiler usually complains about switch statements without
-// case labels. We suppress that warning for this test.
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable: 4065)
-#endif // _MSC_VER
+ // Microsoft compiler usually complains about switch statements without
+ // case labels. We suppress that warning for this test.
+ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
switch (0)
default:
@@ -1355,9 +1417,7 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
case 0:
EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif // _MSC_VER
+ GTEST_DISABLE_MSC_WARNINGS_POP_()
}
// Tests that a test case whose name ends with "DeathTest" works fine
diff --git a/test/gtest-filepath_test.cc b/test/gtest-filepath_test.cc
index ae9f55a..da72986 100644
--- a/test/gtest-filepath_test.cc
+++ b/test/gtest-filepath_test.cc
@@ -514,24 +514,6 @@ class DirectoryCreationTest : public Test {
posix::RmDir(testdata_path_.c_str());
}
- std::string TempDir() const {
-#if GTEST_OS_WINDOWS_MOBILE
- return "\\temp\\";
-#elif GTEST_OS_WINDOWS
- const char* temp_dir = posix::GetEnv("TEMP");
- if (temp_dir == NULL || temp_dir[0] == '\0')
- return "\\temp\\";
- else if (temp_dir[strlen(temp_dir) - 1] == '\\')
- return temp_dir;
- else
- return std::string(temp_dir) + "\\";
-#elif GTEST_OS_LINUX_ANDROID
- return "/sdcard/";
-#else
- return "/tmp/";
-#endif // GTEST_OS_WINDOWS_MOBILE
- }
-
void CreateTextFile(const char* filename) {
FILE* f = posix::FOpen(filename, "w");
fprintf(f, "text\n");
diff --git a/test/gtest-listener_test.cc b/test/gtest-listener_test.cc
index 99662cf..9074768 100644
--- a/test/gtest-listener_test.cc
+++ b/test/gtest-listener_test.cc
@@ -176,16 +176,16 @@ using ::testing::internal::EventRecordingListener;
void VerifyResults(const std::vector<std::string>& data,
const char* const* expected_data,
- int expected_data_size) {
- const int actual_size = data.size();
+ size_t expected_data_size) {
+ const size_t actual_size = data.size();
// If the following assertion fails, a new entry will be appended to
// data. Hence we save data.size() first.
EXPECT_EQ(expected_data_size, actual_size);
// Compares the common prefix.
- const int shorter_size = expected_data_size <= actual_size ?
+ const size_t shorter_size = expected_data_size <= actual_size ?
expected_data_size : actual_size;
- int i = 0;
+ size_t i = 0;
for (; i < shorter_size; ++i) {
ASSERT_STREQ(expected_data[i], data[i].c_str())
<< "at position " << i;
@@ -193,7 +193,8 @@ void VerifyResults(const std::vector<std::string>& data,
// Prints extra elements in the actual data.
for (; i < actual_size; ++i) {
- printf(" Actual event #%d: %s\n", i, data[i].c_str());
+ printf(" Actual event #%lu: %s\n",
+ static_cast<unsigned long>(i), data[i].c_str());
}
}
diff --git a/test/gtest-param-test_test.cc b/test/gtest-param-test_test.cc
index f60cb8a..8b278bb 100644
--- a/test/gtest-param-test_test.cc
+++ b/test/gtest-param-test_test.cc
@@ -64,9 +64,9 @@ using ::testing::ValuesIn;
# if GTEST_HAS_COMBINE
using ::testing::Combine;
-using ::std::tr1::get;
-using ::std::tr1::make_tuple;
-using ::std::tr1::tuple;
+using ::testing::get;
+using ::testing::make_tuple;
+using ::testing::tuple;
# endif // GTEST_HAS_COMBINE
using ::testing::internal::ParamGenerator;
@@ -809,6 +809,157 @@ TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) {
INSTANTIATE_TEST_CASE_P(ZeroToFiveSequence, NamingTest, Range(0, 5));
+// Tests that user supplied custom parameter names are working correctly.
+// Runs the test with a builtin helper method which uses PrintToString,
+// as well as a custom function and custom functor to ensure all possible
+// uses work correctly.
+class CustomFunctorNamingTest : public TestWithParam<std::string> {};
+TEST_P(CustomFunctorNamingTest, CustomTestNames) {}
+
+struct CustomParamNameFunctor {
+ std::string operator()(const ::testing::TestParamInfo<std::string>& info) {
+ return info.param;
+ }
+};
+
+INSTANTIATE_TEST_CASE_P(CustomParamNameFunctor,
+ CustomFunctorNamingTest,
+ Values(std::string("FunctorName")),
+ CustomParamNameFunctor());
+
+INSTANTIATE_TEST_CASE_P(AllAllowedCharacters,
+ CustomFunctorNamingTest,
+ Values("abcdefghijklmnopqrstuvwxyz",
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
+ "01234567890_"),
+ CustomParamNameFunctor());
+
+inline std::string CustomParamNameFunction(
+ const ::testing::TestParamInfo<std::string>& info) {
+ return info.param;
+}
+
+class CustomFunctionNamingTest : public TestWithParam<std::string> {};
+TEST_P(CustomFunctionNamingTest, CustomTestNames) {}
+
+INSTANTIATE_TEST_CASE_P(CustomParamNameFunction,
+ CustomFunctionNamingTest,
+ Values(std::string("FunctionName")),
+ CustomParamNameFunction);
+
+#if GTEST_LANG_CXX11
+
+// Test custom naming with a lambda
+
+class CustomLambdaNamingTest : public TestWithParam<std::string> {};
+TEST_P(CustomLambdaNamingTest, CustomTestNames) {}
+
+INSTANTIATE_TEST_CASE_P(CustomParamNameLambda,
+ CustomLambdaNamingTest,
+ Values(std::string("LambdaName")),
+ [](const ::testing::TestParamInfo<std::string>& info) {
+ return info.param;
+ });
+
+#endif // GTEST_LANG_CXX11
+
+TEST(CustomNamingTest, CheckNameRegistry) {
+ ::testing::UnitTest* unit_test = ::testing::UnitTest::GetInstance();
+ std::set<std::string> test_names;
+ for (int case_num = 0;
+ case_num < unit_test->total_test_case_count();
+ ++case_num) {
+ const ::testing::TestCase* test_case = unit_test->GetTestCase(case_num);
+ for (int test_num = 0;
+ test_num < test_case->total_test_count();
+ ++test_num) {
+ const ::testing::TestInfo* test_info = test_case->GetTestInfo(test_num);
+ test_names.insert(std::string(test_info->name()));
+ }
+ }
+ EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctorName"));
+ EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctionName"));
+#if GTEST_LANG_CXX11
+ EXPECT_EQ(1u, test_names.count("CustomTestNames/LambdaName"));
+#endif // GTEST_LANG_CXX11
+}
+
+// Test a numeric name to ensure PrintToStringParamName works correctly.
+
+class CustomIntegerNamingTest : public TestWithParam<int> {};
+
+TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) {
+ const ::testing::TestInfo* const test_info =
+ ::testing::UnitTest::GetInstance()->current_test_info();
+ Message test_name_stream;
+ test_name_stream << "TestsReportCorrectNames/" << GetParam();
+ EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
+}
+
+INSTANTIATE_TEST_CASE_P(PrintToString,
+ CustomIntegerNamingTest,
+ Range(0, 5),
+ ::testing::PrintToStringParamName());
+
+// Test a custom struct with PrintToString.
+
+struct CustomStruct {
+ explicit CustomStruct(int value) : x(value) {}
+ int x;
+};
+
+std::ostream& operator<<(std::ostream& stream, const CustomStruct& val) {
+ stream << val.x;
+ return stream;
+}
+
+class CustomStructNamingTest : public TestWithParam<CustomStruct> {};
+
+TEST_P(CustomStructNamingTest, TestsReportCorrectNames) {
+ const ::testing::TestInfo* const test_info =
+ ::testing::UnitTest::GetInstance()->current_test_info();
+ Message test_name_stream;
+ test_name_stream << "TestsReportCorrectNames/" << GetParam();
+ EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
+}
+
+INSTANTIATE_TEST_CASE_P(PrintToString,
+ CustomStructNamingTest,
+ Values(CustomStruct(0), CustomStruct(1)),
+ ::testing::PrintToStringParamName());
+
+// Test that using a stateful parameter naming function works as expected.
+
+struct StatefulNamingFunctor {
+ StatefulNamingFunctor() : sum(0) {}
+ std::string operator()(const ::testing::TestParamInfo<int>& info) {
+ int value = info.param + sum;
+ sum += info.param;
+ return ::testing::PrintToString(value);
+ }
+ int sum;
+};
+
+class StatefulNamingTest : public ::testing::TestWithParam<int> {
+ protected:
+ StatefulNamingTest() : sum_(0) {}
+ int sum_;
+};
+
+TEST_P(StatefulNamingTest, TestsReportCorrectNames) {
+ const ::testing::TestInfo* const test_info =
+ ::testing::UnitTest::GetInstance()->current_test_info();
+ sum_ += GetParam();
+ Message test_name_stream;
+ test_name_stream << "TestsReportCorrectNames/" << sum_;
+ EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());
+}
+
+INSTANTIATE_TEST_CASE_P(StatefulNamingFunctor,
+ StatefulNamingTest,
+ Range(0, 5),
+ StatefulNamingFunctor());
+
// Class that cannot be streamed into an ostream. It needs to be copyable
// (and, in case of MSVC, also assignable) in order to be a test parameter
// type. Its default copy constructor and assignment operator do exactly
diff --git a/test/gtest-port_test.cc b/test/gtest-port_test.cc
index 43f1f20..6ea607b 100644
--- a/test/gtest-port_test.cc
+++ b/test/gtest-port_test.cc
@@ -75,8 +75,8 @@ TEST(IsXDigitTest, WorksForNarrowAscii) {
}
TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
- EXPECT_FALSE(IsXDigit(static_cast<char>(0x80)));
- EXPECT_FALSE(IsXDigit(static_cast<char>('0' | 0x80)));
+ EXPECT_FALSE(IsXDigit('\x80'));
+ EXPECT_FALSE(IsXDigit(static_cast<char>('0' | '\x80')));
}
TEST(IsXDigitTest, WorksForWideAscii) {
@@ -304,58 +304,51 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1));
}
-#if GTEST_OS_MAC || GTEST_OS_QNX
+#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX
void* ThreadFunc(void* data) {
- pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(data);
- pthread_mutex_lock(mutex);
- pthread_mutex_unlock(mutex);
+ internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
+ mutex->Lock();
+ mutex->Unlock();
return NULL;
}
TEST(GetThreadCountTest, ReturnsCorrectValue) {
- EXPECT_EQ(1U, GetThreadCount());
- pthread_mutex_t mutex;
- pthread_attr_t attr;
+ const size_t starting_count = GetThreadCount();
pthread_t thread_id;
- // TODO(vladl@google.com): turn mutex into internal::Mutex for automatic
- // destruction.
- pthread_mutex_init(&mutex, NULL);
- pthread_mutex_lock(&mutex);
- ASSERT_EQ(0, pthread_attr_init(&attr));
- ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
-
- const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
- ASSERT_EQ(0, pthread_attr_destroy(&attr));
- ASSERT_EQ(0, status);
- EXPECT_EQ(2U, GetThreadCount());
- pthread_mutex_unlock(&mutex);
+ internal::Mutex mutex;
+ {
+ internal::MutexLock lock(&mutex);
+ pthread_attr_t attr;
+ ASSERT_EQ(0, pthread_attr_init(&attr));
+ ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
+
+ const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
+ ASSERT_EQ(0, pthread_attr_destroy(&attr));
+ ASSERT_EQ(0, status);
+ EXPECT_EQ(starting_count + 1, GetThreadCount());
+ }
void* dummy;
ASSERT_EQ(0, pthread_join(thread_id, &dummy));
-# if GTEST_OS_MAC
-
- // MacOS X may not immediately report the updated thread count after
+ // The OS may not immediately report the updated thread count after
// joining a thread, causing flakiness in this test. To counter that, we
// wait for up to .5 seconds for the OS to report the correct value.
for (int i = 0; i < 5; ++i) {
- if (GetThreadCount() == 1)
+ if (GetThreadCount() == starting_count)
break;
SleepMilliseconds(100);
}
-# endif // GTEST_OS_MAC
-
- EXPECT_EQ(1U, GetThreadCount());
- pthread_mutex_destroy(&mutex);
+ EXPECT_EQ(starting_count, GetThreadCount());
}
#else
TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
EXPECT_EQ(0U, GetThreadCount());
}
-#endif // GTEST_OS_MAC || GTEST_OS_QNX
+#endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX
TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
const bool a_false_condition = false;
@@ -389,15 +382,17 @@ TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
// the platform. The test will produce compiler errors in case of failure.
// For simplicity, we only cover the most important platforms here.
TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
-#if GTEST_HAS_POSIX_RE
+#if !GTEST_USES_PCRE
+# if GTEST_HAS_POSIX_RE
EXPECT_TRUE(GTEST_USES_POSIX_RE);
-#else
+# else
EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
-#endif
+# endif
+#endif // !GTEST_USES_PCRE
}
#if GTEST_USES_POSIX_RE
@@ -1062,11 +1057,13 @@ class AtomicCounterWithMutex {
MutexLock lock(mutex_);
int temp = value_;
{
- // Locking a mutex puts up a memory barrier, preventing reads and
- // writes to value_ rearranged when observed from other threads.
- //
- // We cannot use Mutex and MutexLock here or rely on their memory
- // barrier functionality as we are testing them here.
+ // We need to put up a memory barrier to prevent reads and writes to
+ // value_ rearranged with the call to SleepMilliseconds when observed
+ // from other threads.
+#if GTEST_HAS_PTHREAD
+ // On POSIX, locking a mutex puts up a memory barrier. We cannot use
+ // Mutex and MutexLock here or rely on their memory barrier
+ // functionality as we are testing them here.
pthread_mutex_t memory_barrier_mutex;
GTEST_CHECK_POSIX_SUCCESS_(
pthread_mutex_init(&memory_barrier_mutex, NULL));
@@ -1076,6 +1073,15 @@ class AtomicCounterWithMutex {
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
+#elif GTEST_OS_WINDOWS
+ // On Windows, performing an interlocked access puts up a memory barrier.
+ volatile LONG dummy = 0;
+ ::InterlockedIncrement(&dummy);
+ SleepMilliseconds(random_.Generate(30));
+ ::InterlockedIncrement(&dummy);
+#else
+# error "Memory barrier not implemented on this platform."
+#endif // GTEST_HAS_PTHREAD
}
value_ = temp + 1;
}
@@ -1145,27 +1151,76 @@ TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
EXPECT_STREQ("foo", result.c_str());
}
+// Keeps track of whether of destructors being called on instances of
+// DestructorTracker. On Windows, waits for the destructor call reports.
+class DestructorCall {
+ public:
+ DestructorCall() {
+ invoked_ = false;
+#if GTEST_OS_WINDOWS
+ wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));
+ GTEST_CHECK_(wait_event_.Get() != NULL);
+#endif
+ }
+
+ bool CheckDestroyed() const {
+#if GTEST_OS_WINDOWS
+ if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)
+ return false;
+#endif
+ return invoked_;
+ }
+
+ void ReportDestroyed() {
+ invoked_ = true;
+#if GTEST_OS_WINDOWS
+ ::SetEvent(wait_event_.Get());
+#endif
+ }
+
+ static std::vector<DestructorCall*>& List() { return *list_; }
+
+ static void ResetList() {
+ for (size_t i = 0; i < list_->size(); ++i) {
+ delete list_->at(i);
+ }
+ list_->clear();
+ }
+
+ private:
+ bool invoked_;
+#if GTEST_OS_WINDOWS
+ AutoHandle wait_event_;
+#endif
+ static std::vector<DestructorCall*>* const list_;
+
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall);
+};
+
+std::vector<DestructorCall*>* const DestructorCall::list_ =
+ new std::vector<DestructorCall*>;
+
// DestructorTracker keeps track of whether its instances have been
// destroyed.
-static std::vector<bool> g_destroyed;
-
class DestructorTracker {
public:
DestructorTracker() : index_(GetNewIndex()) {}
DestructorTracker(const DestructorTracker& /* rhs */)
: index_(GetNewIndex()) {}
~DestructorTracker() {
- // We never access g_destroyed concurrently, so we don't need to
- // protect the write operation under a mutex.
- g_destroyed[index_] = true;
+ // We never access DestructorCall::List() concurrently, so we don't need
+ // to protect this acccess with a mutex.
+ DestructorCall::List()[index_]->ReportDestroyed();
}
private:
- static int GetNewIndex() {
- g_destroyed.push_back(false);
- return g_destroyed.size() - 1;
+ static size_t GetNewIndex() {
+ DestructorCall::List().push_back(new DestructorCall);
+ return DestructorCall::List().size() - 1;
}
- const int index_;
+ const size_t index_;
+
+ GTEST_DISALLOW_ASSIGN_(DestructorTracker);
};
typedef ThreadLocal<DestructorTracker>* ThreadParam;
@@ -1177,63 +1232,49 @@ void CallThreadLocalGet(ThreadParam thread_local_param) {
// Tests that when a ThreadLocal object dies in a thread, it destroys
// the managed object for that thread.
TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
- g_destroyed.clear();
+ DestructorCall::ResetList();
{
- // The next line default constructs a DestructorTracker object as
- // the default value of objects managed by thread_local_tracker.
ThreadLocal<DestructorTracker> thread_local_tracker;
- ASSERT_EQ(1U, g_destroyed.size());
- ASSERT_FALSE(g_destroyed[0]);
+ ASSERT_EQ(0U, DestructorCall::List().size());
// This creates another DestructorTracker object for the main thread.
thread_local_tracker.get();
- ASSERT_EQ(2U, g_destroyed.size());
- ASSERT_FALSE(g_destroyed[0]);
- ASSERT_FALSE(g_destroyed[1]);
+ ASSERT_EQ(1U, DestructorCall::List().size());
+ ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());
}
- // Now thread_local_tracker has died. It should have destroyed both the
- // default value shared by all threads and the value for the main
- // thread.
- ASSERT_EQ(2U, g_destroyed.size());
- EXPECT_TRUE(g_destroyed[0]);
- EXPECT_TRUE(g_destroyed[1]);
+ // Now thread_local_tracker has died.
+ ASSERT_EQ(1U, DestructorCall::List().size());
+ EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
- g_destroyed.clear();
+ DestructorCall::ResetList();
}
// Tests that when a thread exits, the thread-local object for that
// thread is destroyed.
TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
- g_destroyed.clear();
+ DestructorCall::ResetList();
{
- // The next line default constructs a DestructorTracker object as
- // the default value of objects managed by thread_local_tracker.
ThreadLocal<DestructorTracker> thread_local_tracker;
- ASSERT_EQ(1U, g_destroyed.size());
- ASSERT_FALSE(g_destroyed[0]);
+ ASSERT_EQ(0U, DestructorCall::List().size());
// This creates another DestructorTracker object in the new thread.
ThreadWithParam<ThreadParam> thread(
&CallThreadLocalGet, &thread_local_tracker, NULL);
thread.Join();
- // Now the new thread has exited. The per-thread object for it
- // should have been destroyed.
- ASSERT_EQ(2U, g_destroyed.size());
- ASSERT_FALSE(g_destroyed[0]);
- ASSERT_TRUE(g_destroyed[1]);
+ // The thread has exited, and we should have a DestroyedTracker
+ // instance created for it. But it may not have been destroyed yet.
+ ASSERT_EQ(1U, DestructorCall::List().size());
}
- // Now thread_local_tracker has died. The default value should have been
- // destroyed too.
- ASSERT_EQ(2U, g_destroyed.size());
- EXPECT_TRUE(g_destroyed[0]);
- EXPECT_TRUE(g_destroyed[1]);
+ // The thread has exited and thread_local_tracker has died.
+ ASSERT_EQ(1U, DestructorCall::List().size());
+ EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());
- g_destroyed.clear();
+ DestructorCall::ResetList();
}
TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
@@ -1249,5 +1290,15 @@ TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
#endif // GTEST_IS_THREADSAFE
+#if GTEST_OS_WINDOWS
+TEST(WindowsTypesTest, HANDLEIsVoidStar) {
+ StaticAssertTypeEq<HANDLE, void*>();
+}
+
+TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {
+ StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();
+}
+#endif // GTEST_OS_WINDOWS
+
} // namespace internal
} // namespace testing
diff --git a/test/gtest-printers_test.cc b/test/gtest-printers_test.cc
index c2beca7..3e97cc2 100644
--- a/test/gtest-printers_test.cc
+++ b/test/gtest-printers_test.cc
@@ -50,13 +50,17 @@
#include "gtest/gtest.h"
-// hash_map and hash_set are available under Visual C++.
-#if _MSC_VER
-# define GTEST_HAS_HASH_MAP_ 1 // Indicates that hash_map is available.
+// hash_map and hash_set are available under Visual C++, or on Linux.
+#if GTEST_HAS_HASH_MAP_
# include <hash_map> // NOLINT
-# define GTEST_HAS_HASH_SET_ 1 // Indicates that hash_set is available.
+#endif // GTEST_HAS_HASH_MAP_
+#if GTEST_HAS_HASH_SET_
# include <hash_set> // NOLINT
-#endif // GTEST_OS_WINDOWS
+#endif // GTEST_HAS_HASH_SET_
+
+#if GTEST_HAS_STD_FORWARD_LIST_
+# include <forward_list> // NOLINT
+#endif // GTEST_HAS_STD_FORWARD_LIST_
// Some user-defined types for testing the universal value printer.
@@ -125,6 +129,7 @@ namespace foo {
class UnprintableInFoo {
public:
UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
+ double z() const { return z_; }
private:
char xy_[8];
double z_;
@@ -201,19 +206,14 @@ using ::testing::internal::FormatForComparisonFailureMessage;
using ::testing::internal::ImplicitCast_;
using ::testing::internal::NativeArray;
using ::testing::internal::RE;
+using ::testing::internal::RelationToSourceReference;
using ::testing::internal::Strings;
using ::testing::internal::UniversalPrint;
using ::testing::internal::UniversalPrinter;
using ::testing::internal::UniversalTersePrint;
using ::testing::internal::UniversalTersePrintTupleFieldsToStrings;
-using ::testing::internal::kReference;
using ::testing::internal::string;
-#if GTEST_HAS_TR1_TUPLE
-using ::std::tr1::make_tuple;
-using ::std::tr1::tuple;
-#endif
-
// The hash_* classes are not part of the C++ standard. STLport
// defines them in namespace std. MSVC defines them in ::stdext. GCC
// defines them in ::.
@@ -414,8 +414,6 @@ TEST(PrintCStringTest, EscapesProperly) {
Print(p));
}
-
-
// MSVC compiler can be configured to define whar_t as a typedef
// of unsigned short. Defining an overload for const wchar_t* in that case
// would cause pointers to unsigned shorts be printed as wide strings,
@@ -919,6 +917,17 @@ TEST(PrintStlContainerTest, MultiSet) {
EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
}
+#if GTEST_HAS_STD_FORWARD_LIST_
+// <slist> is available on Linux in the google3 mode, but not on
+// Windows or Mac OS X.
+
+TEST(PrintStlContainerTest, SinglyLinkedList) {
+ int a[] = { 9, 2, 8 };
+ const std::forward_list<int> ints(a, a + 3);
+ EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
+}
+#endif // GTEST_HAS_STD_FORWARD_LIST_
+
TEST(PrintStlContainerTest, Pair) {
pair<const bool, int> p(true, 5);
EXPECT_EQ("(true, 5)", Print(p));
@@ -952,13 +961,13 @@ TEST(PrintStlContainerTest, NestedContainer) {
TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
const int a[3] = { 1, 2, 3 };
- NativeArray<int> b(a, 3, kReference);
+ NativeArray<int> b(a, 3, RelationToSourceReference());
EXPECT_EQ("{ 1, 2, 3 }", Print(b));
}
TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
- NativeArray<int[3]> b(a, 2, kReference);
+ NativeArray<int[3]> b(a, 2, RelationToSourceReference());
EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
}
@@ -985,46 +994,47 @@ TEST(PrintStlContainerTest, ConstIterator) {
}
#if GTEST_HAS_TR1_TUPLE
-// Tests printing tuples.
+// Tests printing ::std::tr1::tuples.
// Tuples of various arities.
-TEST(PrintTupleTest, VariousSizes) {
- tuple<> t0;
+TEST(PrintTr1TupleTest, VariousSizes) {
+ ::std::tr1::tuple<> t0;
EXPECT_EQ("()", Print(t0));
- tuple<int> t1(5);
+ ::std::tr1::tuple<int> t1(5);
EXPECT_EQ("(5)", Print(t1));
- tuple<char, bool> t2('a', true);
+ ::std::tr1::tuple<char, bool> t2('a', true);
EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
- tuple<bool, int, int> t3(false, 2, 3);
+ ::std::tr1::tuple<bool, int, int> t3(false, 2, 3);
EXPECT_EQ("(false, 2, 3)", Print(t3));
- tuple<bool, int, int, int> t4(false, 2, 3, 4);
+ ::std::tr1::tuple<bool, int, int, int> t4(false, 2, 3, 4);
EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
- tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true);
+ ::std::tr1::tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true);
EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5));
- tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6);
+ ::std::tr1::tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6);
EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6));
- tuple<bool, int, int, int, bool, int, int> t7(false, 2, 3, 4, true, 6, 7);
+ ::std::tr1::tuple<bool, int, int, int, bool, int, int> t7(
+ false, 2, 3, 4, true, 6, 7);
EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7));
- tuple<bool, int, int, int, bool, int, int, bool> t8(
+ ::std::tr1::tuple<bool, int, int, int, bool, int, int, bool> t8(
false, 2, 3, 4, true, 6, 7, true);
EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8));
- tuple<bool, int, int, int, bool, int, int, bool, int> t9(
+ ::std::tr1::tuple<bool, int, int, int, bool, int, int, bool, int> t9(
false, 2, 3, 4, true, 6, 7, true, 9);
EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9));
const char* const str = "8";
// VC++ 2010's implementation of tuple of C++0x is deficient, requiring
// an explicit type cast of NULL to be used.
- tuple<bool, char, short, testing::internal::Int32, // NOLINT
+ ::std::tr1::tuple<bool, char, short, testing::internal::Int32, // NOLINT
testing::internal::Int64, float, double, const char*, void*, string>
t10(false, 'a', 3, 4, 5, 1.5F, -2.5, str,
ImplicitCast_<void*>(NULL), "10");
@@ -1034,13 +1044,73 @@ TEST(PrintTupleTest, VariousSizes) {
}
// Nested tuples.
-TEST(PrintTupleTest, NestedTuple) {
- tuple<tuple<int, bool>, char> nested(make_tuple(5, true), 'a');
+TEST(PrintTr1TupleTest, NestedTuple) {
+ ::std::tr1::tuple< ::std::tr1::tuple<int, bool>, char> nested(
+ ::std::tr1::make_tuple(5, true), 'a');
EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
}
#endif // GTEST_HAS_TR1_TUPLE
+#if GTEST_HAS_STD_TUPLE_
+// Tests printing ::std::tuples.
+
+// Tuples of various arities.
+TEST(PrintStdTupleTest, VariousSizes) {
+ ::std::tuple<> t0;
+ EXPECT_EQ("()", Print(t0));
+
+ ::std::tuple<int> t1(5);
+ EXPECT_EQ("(5)", Print(t1));
+
+ ::std::tuple<char, bool> t2('a', true);
+ EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
+
+ ::std::tuple<bool, int, int> t3(false, 2, 3);
+ EXPECT_EQ("(false, 2, 3)", Print(t3));
+
+ ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4);
+ EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
+
+ ::std::tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true);
+ EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5));
+
+ ::std::tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6);
+ EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6));
+
+ ::std::tuple<bool, int, int, int, bool, int, int> t7(
+ false, 2, 3, 4, true, 6, 7);
+ EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7));
+
+ ::std::tuple<bool, int, int, int, bool, int, int, bool> t8(
+ false, 2, 3, 4, true, 6, 7, true);
+ EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8));
+
+ ::std::tuple<bool, int, int, int, bool, int, int, bool, int> t9(
+ false, 2, 3, 4, true, 6, 7, true, 9);
+ EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9));
+
+ const char* const str = "8";
+ // VC++ 2010's implementation of tuple of C++0x is deficient, requiring
+ // an explicit type cast of NULL to be used.
+ ::std::tuple<bool, char, short, testing::internal::Int32, // NOLINT
+ testing::internal::Int64, float, double, const char*, void*, string>
+ t10(false, 'a', 3, 4, 5, 1.5F, -2.5, str,
+ ImplicitCast_<void*>(NULL), "10");
+ EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
+ " pointing to \"8\", NULL, \"10\")",
+ Print(t10));
+}
+
+// Nested tuples.
+TEST(PrintStdTupleTest, NestedTuple) {
+ ::std::tuple< ::std::tuple<int, bool>, char> nested(
+ ::std::make_tuple(5, true), 'a');
+ EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
+}
+
+#endif // GTEST_LANG_CXX11
+
// Tests printing user-defined unprintable types.
// Unprintable types in the global namespace.
@@ -1107,44 +1177,6 @@ TEST(PrintPrintableTypeTest, TemplateInUserNamespace) {
Print(::foo::PrintableViaPrintToTemplate<int>(5)));
}
-#if GTEST_HAS_PROTOBUF_
-
-// Tests printing a protocol message.
-TEST(PrintProtocolMessageTest, PrintsShortDebugString) {
- testing::internal::TestMessage msg;
- msg.set_member("yes");
- EXPECT_EQ("<member:\"yes\">", Print(msg));
-}
-
-// Tests printing a short proto2 message.
-TEST(PrintProto2MessageTest, PrintsShortDebugStringWhenItIsShort) {
- testing::internal::FooMessage msg;
- msg.set_int_field(2);
- msg.set_string_field("hello");
- EXPECT_PRED2(RE::FullMatch, Print(msg),
- "<int_field:\\s*2\\s+string_field:\\s*\"hello\">");
-}
-
-// Tests printing a long proto2 message.
-TEST(PrintProto2MessageTest, PrintsDebugStringWhenItIsLong) {
- testing::internal::FooMessage msg;
- msg.set_int_field(2);
- msg.set_string_field("hello");
- msg.add_names("peter");
- msg.add_names("paul");
- msg.add_names("mary");
- EXPECT_PRED2(RE::FullMatch, Print(msg),
- "<\n"
- "int_field:\\s*2\n"
- "string_field:\\s*\"hello\"\n"
- "names:\\s*\"peter\"\n"
- "names:\\s*\"paul\"\n"
- "names:\\s*\"mary\"\n"
- ">");
-}
-
-#endif // GTEST_HAS_PROTOBUF_
-
// Tests that the universal printer prints both the address and the
// value of a reference.
TEST(PrintReferenceTest, PrintsAddressAndValue) {
@@ -1533,28 +1565,31 @@ TEST(UniversalPrintTest, WorksForCharArray) {
#if GTEST_HAS_TR1_TUPLE
-TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsEmptyTuple) {
- Strings result = UniversalTersePrintTupleFieldsToStrings(make_tuple());
+TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsEmptyTuple) {
+ Strings result = UniversalTersePrintTupleFieldsToStrings(
+ ::std::tr1::make_tuple());
EXPECT_EQ(0u, result.size());
}
-TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsOneTuple) {
- Strings result = UniversalTersePrintTupleFieldsToStrings(make_tuple(1));
+TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsOneTuple) {
+ Strings result = UniversalTersePrintTupleFieldsToStrings(
+ ::std::tr1::make_tuple(1));
ASSERT_EQ(1u, result.size());
EXPECT_EQ("1", result[0]);
}
-TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsTwoTuple) {
- Strings result = UniversalTersePrintTupleFieldsToStrings(make_tuple(1, 'a'));
+TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTwoTuple) {
+ Strings result = UniversalTersePrintTupleFieldsToStrings(
+ ::std::tr1::make_tuple(1, 'a'));
ASSERT_EQ(2u, result.size());
EXPECT_EQ("1", result[0]);
EXPECT_EQ("'a' (97, 0x61)", result[1]);
}
-TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsTersely) {
+TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTersely) {
const int n = 1;
Strings result = UniversalTersePrintTupleFieldsToStrings(
- tuple<const int&, const char*>(n, "a"));
+ ::std::tr1::tuple<const int&, const char*>(n, "a"));
ASSERT_EQ(2u, result.size());
EXPECT_EQ("1", result[0]);
EXPECT_EQ("\"a\"", result[1]);
@@ -1562,5 +1597,39 @@ TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsTersely) {
#endif // GTEST_HAS_TR1_TUPLE
+#if GTEST_HAS_STD_TUPLE_
+
+TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
+ Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
+ EXPECT_EQ(0u, result.size());
+}
+
+TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
+ Strings result = UniversalTersePrintTupleFieldsToStrings(
+ ::std::make_tuple(1));
+ ASSERT_EQ(1u, result.size());
+ EXPECT_EQ("1", result[0]);
+}
+
+TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
+ Strings result = UniversalTersePrintTupleFieldsToStrings(
+ ::std::make_tuple(1, 'a'));
+ ASSERT_EQ(2u, result.size());
+ EXPECT_EQ("1", result[0]);
+ EXPECT_EQ("'a' (97, 0x61)", result[1]);
+}
+
+TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
+ const int n = 1;
+ Strings result = UniversalTersePrintTupleFieldsToStrings(
+ ::std::tuple<const int&, const char*>(n, "a"));
+ ASSERT_EQ(2u, result.size());
+ EXPECT_EQ("1", result[0]);
+ EXPECT_EQ("\"a\"", result[1]);
+}
+
+#endif // GTEST_HAS_STD_TUPLE_
+
} // namespace gtest_printers_test
} // namespace testing
+
diff --git a/test/gtest-typed-test_test.cc b/test/gtest-typed-test_test.cc
index dd4ba43..93628ba 100644
--- a/test/gtest-typed-test_test.cc
+++ b/test/gtest-typed-test_test.cc
@@ -29,10 +29,11 @@
//
// Author: wan@google.com (Zhanyong Wan)
+#include "test/gtest-typed-test_test.h"
+
#include <set>
#include <vector>
-#include "test/gtest-typed-test_test.h"
#include "gtest/gtest.h"
using testing::Test;
@@ -343,6 +344,25 @@ REGISTER_TYPED_TEST_CASE_P(NumericTest,
typedef Types<int, double> NumericTypes;
INSTANTIATE_TYPED_TEST_CASE_P(My, NumericTest, NumericTypes);
+static const char* GetTestName() {
+ return testing::UnitTest::GetInstance()->current_test_info()->name();
+}
+// Test the stripping of space from test names
+template <typename T> class TrimmedTest : public Test { };
+TYPED_TEST_CASE_P(TrimmedTest);
+TYPED_TEST_P(TrimmedTest, Test1) { EXPECT_STREQ("Test1", GetTestName()); }
+TYPED_TEST_P(TrimmedTest, Test2) { EXPECT_STREQ("Test2", GetTestName()); }
+TYPED_TEST_P(TrimmedTest, Test3) { EXPECT_STREQ("Test3", GetTestName()); }
+TYPED_TEST_P(TrimmedTest, Test4) { EXPECT_STREQ("Test4", GetTestName()); }
+TYPED_TEST_P(TrimmedTest, Test5) { EXPECT_STREQ("Test5", GetTestName()); }
+REGISTER_TYPED_TEST_CASE_P(
+ TrimmedTest,
+ Test1, Test2,Test3 , Test4 ,Test5 ); // NOLINT
+template <typename T1, typename T2> struct MyPair {};
+// Be sure to try a type with a comma in its name just in case it matters.
+typedef Types<int, double, MyPair<int, int> > TrimTypes;
+INSTANTIATE_TYPED_TEST_CASE_P(My, TrimmedTest, TrimTypes);
+
} // namespace library2
#endif // GTEST_HAS_TYPED_TEST_P
diff --git a/test/gtest-unittest-api_test.cc b/test/gtest-unittest-api_test.cc
index 07083e5..b1f5168 100644
--- a/test/gtest-unittest-api_test.cc
+++ b/test/gtest-unittest-api_test.cc
@@ -54,7 +54,7 @@ class UnitTestHelper {
public:
// Returns the array of pointers to all test cases sorted by the test case
// name. The caller is responsible for deleting the array.
- static TestCase const** const GetSortedTestCases() {
+ static TestCase const** GetSortedTestCases() {
UnitTest& unit_test = *UnitTest::GetInstance();
TestCase const** const test_cases =
new const TestCase*[unit_test.total_test_case_count()];
@@ -83,7 +83,7 @@ class UnitTestHelper {
// Returns the array of pointers to all tests in a particular test case
// sorted by the test name. The caller is responsible for deleting the
// array.
- static TestInfo const** const GetSortedTests(const TestCase* test_case) {
+ static TestInfo const** GetSortedTests(const TestCase* test_case) {
TestInfo const** const tests =
new const TestInfo*[test_case->total_test_count()];
diff --git a/test/gtest_env_var_test.py b/test/gtest_env_var_test.py
index ac24337..424075c 100755
--- a/test/gtest_env_var_test.py
+++ b/test/gtest_env_var_test.py
@@ -47,8 +47,8 @@ environ = os.environ.copy()
def AssertEq(expected, actual):
if expected != actual:
- print 'Expected: %s' % (expected,)
- print ' Actual: %s' % (actual,)
+ print('Expected: %s' % (expected,))
+ print(' Actual: %s' % (actual,))
raise AssertionError
@@ -87,6 +87,7 @@ class GTestEnvVarTest(gtest_test_utils.TestCase):
TestFlag('break_on_failure', '1', '0')
TestFlag('color', 'yes', 'auto')
TestFlag('filter', 'FooTest.Bar', '*')
+ SetEnvVar('XML_OUTPUT_FILE', None) # For 'output' test
TestFlag('output', 'xml:tmp/foo.xml', '')
TestFlag('print_time', '0', '1')
TestFlag('repeat', '999', '1')
@@ -98,6 +99,19 @@ class GTestEnvVarTest(gtest_test_utils.TestCase):
TestFlag('death_test_use_fork', '1', '0')
TestFlag('stack_trace_depth', '0', '100')
+ def testXmlOutputFile(self):
+ """Tests that $XML_OUTPUT_FILE affects the output flag."""
+
+ SetEnvVar('GTEST_OUTPUT', None)
+ SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml')
+ AssertEq('xml:tmp/bar.xml', GetFlag('output'))
+
+ def testXmlOutputFileOverride(self):
+ """Tests that $XML_OUTPUT_FILE is overridden by $GTEST_OUTPUT"""
+
+ SetEnvVar('GTEST_OUTPUT', 'xml:tmp/foo.xml')
+ SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml')
+ AssertEq('xml:tmp/foo.xml', GetFlag('output'))
if __name__ == '__main__':
gtest_test_utils.Main()
diff --git a/test/gtest_filter_unittest.py b/test/gtest_filter_unittest.py
index 0d1a770..ec0b151 100755
--- a/test/gtest_filter_unittest.py
+++ b/test/gtest_filter_unittest.py
@@ -44,7 +44,10 @@ __author__ = 'wan@google.com (Zhanyong Wan)'
import os
import re
-import sets
+try:
+ from sets import Set as set # For Python 2.3 compatibility
+except ImportError:
+ pass
import sys
import gtest_test_utils
@@ -58,7 +61,7 @@ import gtest_test_utils
# exception is thrown if the input is anything other than 'True' nor 'False'.
os.environ['EMPTY_VAR'] = ''
child = gtest_test_utils.Subprocess(
- [sys.executable, '-c', 'import os; print \'EMPTY_VAR\' in os.environ'])
+ [sys.executable, '-c', 'import os; print(\'EMPTY_VAR\' in os.environ)'])
CAN_PASS_EMPTY_ENV = eval(child.output)
@@ -71,7 +74,7 @@ CAN_PASS_EMPTY_ENV = eval(child.output)
os.environ['UNSET_VAR'] = 'X'
del os.environ['UNSET_VAR']
child = gtest_test_utils.Subprocess(
- [sys.executable, '-c', 'import os; print \'UNSET_VAR\' not in os.environ'])
+ [sys.executable, '-c', 'import os; print(\'UNSET_VAR\' not in os.environ)'])
CAN_UNSET_ENV = eval(child.output)
@@ -243,14 +246,14 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
for slice_var in list_of_sets:
full_partition.extend(slice_var)
self.assertEqual(len(set_var), len(full_partition))
- self.assertEqual(sets.Set(set_var), sets.Set(full_partition))
+ self.assertEqual(set(set_var), set(full_partition))
def AdjustForParameterizedTests(self, tests_to_run):
"""Adjust tests_to_run in case value parameterized tests are disabled."""
global param_tests_present
if not param_tests_present:
- return list(sets.Set(tests_to_run) - sets.Set(PARAM_TESTS))
+ return list(set(tests_to_run) - set(PARAM_TESTS))
else:
return tests_to_run
diff --git a/test/gtest_list_tests_unittest.py b/test/gtest_list_tests_unittest.py
index 925b09d..f2d2fd1 100755
--- a/test/gtest_list_tests_unittest.py
+++ b/test/gtest_list_tests_unittest.py
@@ -71,7 +71,7 @@ FooTest\.
TypedTest/0\. # TypeParam = (VeryLo{245}|class VeryLo{239})\.\.\.
TestA
TestB
-TypedTest/1\. # TypeParam = int\s*\*
+TypedTest/1\. # TypeParam = int\s*\*( __ptr64)?
TestA
TestB
TypedTest/2\. # TypeParam = .*MyArray<bool,\s*42>
@@ -80,7 +80,7 @@ TypedTest/2\. # TypeParam = .*MyArray<bool,\s*42>
My/TypeParamTest/0\. # TypeParam = (VeryLo{245}|class VeryLo{239})\.\.\.
TestA
TestB
-My/TypeParamTest/1\. # TypeParam = int\s*\*
+My/TypeParamTest/1\. # TypeParam = int\s*\*( __ptr64)?
TestA
TestB
My/TypeParamTest/2\. # TypeParam = .*MyArray<bool,\s*42>
diff --git a/test/gtest_output_test.py b/test/gtest_output_test.py
index f409e2a..06dbee0 100755
--- a/test/gtest_output_test.py
+++ b/test/gtest_output_test.py
@@ -40,6 +40,7 @@ SYNOPSIS
__author__ = 'wan@google.com (Zhanyong Wan)'
+import difflib
import os
import re
import sys
@@ -58,22 +59,22 @@ GOLDEN_NAME = 'gtest_output_test_golden_lin.txt'
PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_output_test_')
# At least one command we exercise must not have the
-# --gtest_internal_skip_environment_and_ad_hoc_tests flag.
+# 'internal_skip_environment_and_ad_hoc_tests' argument.
COMMAND_LIST_TESTS = ({}, [PROGRAM_PATH, '--gtest_list_tests'])
COMMAND_WITH_COLOR = ({}, [PROGRAM_PATH, '--gtest_color=yes'])
COMMAND_WITH_TIME = ({}, [PROGRAM_PATH,
'--gtest_print_time',
- '--gtest_internal_skip_environment_and_ad_hoc_tests',
+ 'internal_skip_environment_and_ad_hoc_tests',
'--gtest_filter=FatalFailureTest.*:LoggingTest.*'])
COMMAND_WITH_DISABLED = (
{}, [PROGRAM_PATH,
'--gtest_also_run_disabled_tests',
- '--gtest_internal_skip_environment_and_ad_hoc_tests',
+ 'internal_skip_environment_and_ad_hoc_tests',
'--gtest_filter=*DISABLED_*'])
COMMAND_WITH_SHARDING = (
{'GTEST_SHARD_INDEX': '1', 'GTEST_TOTAL_SHARDS': '2'},
[PROGRAM_PATH,
- '--gtest_internal_skip_environment_and_ad_hoc_tests',
+ 'internal_skip_environment_and_ad_hoc_tests',
'--gtest_filter=PassingTest.*'])
GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME)
@@ -252,8 +253,8 @@ SUPPORTS_STACK_TRACES = False
CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and
SUPPORTS_TYPED_TESTS and
- SUPPORTS_THREADS)
-
+ SUPPORTS_THREADS and
+ not IS_WINDOWS)
class GTestOutputTest(gtest_test_utils.TestCase):
def RemoveUnsupportedTests(self, test_output):
@@ -278,7 +279,7 @@ class GTestOutputTest(gtest_test_utils.TestCase):
def testOutput(self):
output = GetOutputOfAllCommands()
- golden_file = open(GOLDEN_PATH, 'rb')
+ golden_file = open(GOLDEN_PATH, 'r')
# A mis-configured source control system can cause \r appear in EOL
# sequences when we read the golden file irrespective of an operating
# system used. Therefore, we need to strip those \r's from newlines
@@ -294,7 +295,11 @@ class GTestOutputTest(gtest_test_utils.TestCase):
normalized_golden = RemoveTypeInfoDetails(golden)
if CAN_GENERATE_GOLDEN_FILE:
- self.assertEqual(normalized_golden, normalized_actual)
+ self.assertEqual(normalized_golden, normalized_actual,
+ '\n'.join(difflib.unified_diff(
+ normalized_golden.split('\n'),
+ normalized_actual.split('\n'),
+ 'golden', 'actual')))
else:
normalized_actual = NormalizeToCurrentPlatform(
RemoveTestCounts(normalized_actual))
diff --git a/test/gtest_output_test_.cc b/test/gtest_output_test_.cc
index 07ab633..1070a9f 100644
--- a/test/gtest_output_test_.cc
+++ b/test/gtest_output_test_.cc
@@ -58,7 +58,6 @@ using testing::internal::ThreadWithParam;
#endif
namespace posix = ::testing::internal::posix;
-using testing::internal::scoped_ptr;
// Tests catching fatal failures.
@@ -113,6 +112,11 @@ TEST(NonfatalFailureTest, EscapesStringOperands) {
EXPECT_EQ(golden, actual);
}
+TEST(NonfatalFailureTest, DiffForLongStrings) {
+ std::string golden_str(kGoldenString, sizeof(kGoldenString) - 1);
+ EXPECT_EQ(golden_str, "Line 2");
+}
+
// Tests catching a fatal failure in a subroutine.
TEST(FatalFailureTest, FatalFailureInSubroutine) {
printf("(expecting a failure that x should be 1)\n");
@@ -510,7 +514,8 @@ class DeathTestAndMultiThreadsTest : public testing::Test {
private:
SpawnThreadNotifications notifications_;
- scoped_ptr<ThreadWithParam<SpawnThreadNotifications*> > thread_;
+ testing::internal::scoped_ptr<ThreadWithParam<SpawnThreadNotifications*> >
+ thread_;
};
#endif // GTEST_IS_THREADSAFE
@@ -750,6 +755,32 @@ TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
#endif // GTEST_HAS_EXCEPTIONS
+// This #ifdef block tests the output of value-parameterized tests.
+
+#if GTEST_HAS_PARAM_TEST
+
+std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) {
+ return info.param;
+}
+
+class ParamTest : public testing::TestWithParam<std::string> {
+};
+
+TEST_P(ParamTest, Success) {
+ EXPECT_EQ("a", GetParam());
+}
+
+TEST_P(ParamTest, Failure) {
+ EXPECT_EQ("b", GetParam()) << "Expected failure";
+}
+
+INSTANTIATE_TEST_CASE_P(PrintingStrings,
+ ParamTest,
+ testing::Values(std::string("a")),
+ ParamNameFunc);
+
+#endif // GTEST_HAS_PARAM_TEST
+
// This #ifdef block tests the output of typed tests.
#if GTEST_HAS_TYPED_TEST
@@ -985,8 +1016,6 @@ class BarEnvironment : public testing::Environment {
}
};
-bool GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests) = false;
-
// The main function.
//
// The idea is to use Google Test to run all the tests we have defined (some
@@ -1003,10 +1032,9 @@ int main(int argc, char **argv) {
// global side effects. The following line serves as a sanity test
// for it.
testing::InitGoogleTest(&argc, argv);
- if (argc >= 2 &&
- (std::string(argv[1]) ==
- "--gtest_internal_skip_environment_and_ad_hoc_tests"))
- GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests) = true;
+ bool internal_skip_environment_and_ad_hoc_tests =
+ std::count(argv, argv + argc,
+ std::string("internal_skip_environment_and_ad_hoc_tests")) > 0;
#if GTEST_HAS_DEATH_TEST
if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") {
@@ -1021,7 +1049,7 @@ int main(int argc, char **argv) {
}
#endif // GTEST_HAS_DEATH_TEST
- if (GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests))
+ if (internal_skip_environment_and_ad_hoc_tests)
return RUN_ALL_TESTS();
// Registers two global test environments.
diff --git a/test/gtest_output_test_golden_lin.txt b/test/gtest_output_test_golden_lin.txt
index 960eedc..2223d56 100644
--- a/test/gtest_output_test_golden_lin.txt
+++ b/test/gtest_output_test_golden_lin.txt
@@ -5,9 +5,9 @@ Value of: false
Actual: false
Expected: true
gtest_output_test_.cc:#: Failure
-Value of: 3
-Expected: 2
-[==========] Running 63 tests from 28 test cases.
+ Expected: 2
+To be equal to: 3
+[==========] Running 66 tests from 29 test cases.
[----------] Global test environment set-up.
FooEnvironment::SetUp() called.
BarEnvironment::SetUp() called.
@@ -31,33 +31,44 @@ BarEnvironment::SetUp() called.
[ OK ] PassingTest.PassingTest1
[ RUN ] PassingTest.PassingTest2
[ OK ] PassingTest.PassingTest2
-[----------] 1 test from NonfatalFailureTest
+[----------] 2 tests from NonfatalFailureTest
[ RUN ] NonfatalFailureTest.EscapesStringOperands
gtest_output_test_.cc:#: Failure
-Value of: actual
- Actual: "actual \"string\""
-Expected: kGoldenString
-Which is: "\"Line"
+ Expected: kGoldenString
+ Which is: "\"Line"
+To be equal to: actual
+ Which is: "actual \"string\""
gtest_output_test_.cc:#: Failure
-Value of: actual
- Actual: "actual \"string\""
-Expected: golden
-Which is: "\"Line"
+ Expected: golden
+ Which is: "\"Line"
+To be equal to: actual
+ Which is: "actual \"string\""
[ FAILED ] NonfatalFailureTest.EscapesStringOperands
+[ RUN ] NonfatalFailureTest.DiffForLongStrings
+gtest_output_test_.cc:#: Failure
+ Expected: golden_str
+ Which is: "\"Line\0 1\"\nLine 2"
+To be equal to: "Line 2"
+With diff:
+@@ -1,2 @@
+-\"Line\0 1\"
+ Line 2
+
+[ FAILED ] NonfatalFailureTest.DiffForLongStrings
[----------] 3 tests from FatalFailureTest
[ RUN ] FatalFailureTest.FatalFailureInSubroutine
(expecting a failure that x should be 1)
gtest_output_test_.cc:#: Failure
-Value of: x
- Actual: 2
-Expected: 1
+ Expected: 1
+To be equal to: x
+ Which is: 2
[ FAILED ] FatalFailureTest.FatalFailureInSubroutine
[ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine
(expecting a failure that x should be 1)
gtest_output_test_.cc:#: Failure
-Value of: x
- Actual: 2
-Expected: 1
+ Expected: 1
+To be equal to: x
+ Which is: 2
[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine
[ RUN ] FatalFailureTest.NonfatalFailureInSubroutine
(expecting a failure on false)
@@ -96,39 +107,39 @@ This failure is expected, and shouldn't have a trace.
[ RUN ] SCOPED_TRACETest.WorksInLoop
(expected to fail)
gtest_output_test_.cc:#: Failure
-Value of: n
- Actual: 1
-Expected: 2
+ Expected: 2
+To be equal to: n
+ Which is: 1
Google Test trace:
gtest_output_test_.cc:#: i = 1
gtest_output_test_.cc:#: Failure
-Value of: n
- Actual: 2
-Expected: 1
+ Expected: 1
+To be equal to: n
+ Which is: 2
Google Test trace:
gtest_output_test_.cc:#: i = 2
[ FAILED ] SCOPED_TRACETest.WorksInLoop
[ RUN ] SCOPED_TRACETest.WorksInSubroutine
(expected to fail)
gtest_output_test_.cc:#: Failure
-Value of: n
- Actual: 1
-Expected: 2
+ Expected: 2
+To be equal to: n
+ Which is: 1
Google Test trace:
gtest_output_test_.cc:#: n = 1
gtest_output_test_.cc:#: Failure
-Value of: n
- Actual: 2
-Expected: 1
+ Expected: 1
+To be equal to: n
+ Which is: 2
Google Test trace:
gtest_output_test_.cc:#: n = 2
[ FAILED ] SCOPED_TRACETest.WorksInSubroutine
[ RUN ] SCOPED_TRACETest.CanBeNested
(expected to fail)
gtest_output_test_.cc:#: Failure
-Value of: n
- Actual: 2
-Expected: 1
+ Expected: 1
+To be equal to: n
+ Which is: 2
Google Test trace:
gtest_output_test_.cc:#: n = 2
gtest_output_test_.cc:#:
@@ -426,9 +437,9 @@ Expected: 1 fatal failure
[ OK ] TypedTest/0.Success
[ RUN ] TypedTest/0.Failure
gtest_output_test_.cc:#: Failure
-Value of: TypeParam()
- Actual: 0
-Expected: 1
+ Expected: 1
+To be equal to: TypeParam()
+ Which is: 0
Expected failure
[ FAILED ] TypedTest/0.Failure, where TypeParam = int
[----------] 2 tests from Unsigned/TypedTestP/0, where TypeParam = unsigned char
@@ -436,10 +447,10 @@ Expected failure
[ OK ] Unsigned/TypedTestP/0.Success
[ RUN ] Unsigned/TypedTestP/0.Failure
gtest_output_test_.cc:#: Failure
-Value of: TypeParam()
- Actual: '\0'
-Expected: 1U
-Which is: 1
+ Expected: 1U
+ Which is: 1
+To be equal to: TypeParam()
+ Which is: '\0'
Expected failure
[ FAILED ] Unsigned/TypedTestP/0.Failure, where TypeParam = unsigned char
[----------] 2 tests from Unsigned/TypedTestP/1, where TypeParam = unsigned int
@@ -447,10 +458,10 @@ Expected failure
[ OK ] Unsigned/TypedTestP/1.Success
[ RUN ] Unsigned/TypedTestP/1.Failure
gtest_output_test_.cc:#: Failure
-Value of: TypeParam()
- Actual: 0
-Expected: 1U
-Which is: 1
+ Expected: 1U
+ Which is: 1
+To be equal to: TypeParam()
+ Which is: 0
Expected failure
[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int
[----------] 4 tests from ExpectFailureTest
@@ -586,10 +597,20 @@ Expected non-fatal failure.
[----------] 1 test from PrintingFailingParams/FailingParamTest
[ RUN ] PrintingFailingParams/FailingParamTest.Fails/0
gtest_output_test_.cc:#: Failure
-Value of: GetParam()
- Actual: 2
-Expected: 1
+ Expected: 1
+To be equal to: GetParam()
+ Which is: 2
[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2
+[----------] 2 tests from PrintingStrings/ParamTest
+[ RUN ] PrintingStrings/ParamTest.Success/a
+[ OK ] PrintingStrings/ParamTest.Success/a
+[ RUN ] PrintingStrings/ParamTest.Failure/a
+gtest_output_test_.cc:#: Failure
+ Expected: "b"
+To be equal to: GetParam()
+ Which is: "a"
+Expected failure
+[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a"
[----------] Global test environment tear-down
BarEnvironment::TearDown() called.
gtest_output_test_.cc:#: Failure
@@ -599,10 +620,11 @@ FooEnvironment::TearDown() called.
gtest_output_test_.cc:#: Failure
Failed
Expected fatal failure.
-[==========] 63 tests from 28 test cases ran.
-[ PASSED ] 21 tests.
-[ FAILED ] 42 tests, listed below:
+[==========] 66 tests from 29 test cases ran.
+[ PASSED ] 22 tests.
+[ FAILED ] 44 tests, listed below:
[ FAILED ] NonfatalFailureTest.EscapesStringOperands
+[ FAILED ] NonfatalFailureTest.DiffForLongStrings
[ FAILED ] FatalFailureTest.FatalFailureInSubroutine
[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine
[ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine
@@ -644,8 +666,9 @@ Expected fatal failure.
[ FAILED ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure
[ FAILED ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread
[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2
+[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a"
-42 FAILED TESTS
+44 FAILED TESTS
 YOU HAVE 1 DISABLED TEST
Note: Google Test filter = FatalFailureTest.*:LoggingTest.*
@@ -655,16 +678,16 @@ Expected fatal failure.
[ RUN ] FatalFailureTest.FatalFailureInSubroutine
(expecting a failure that x should be 1)
gtest_output_test_.cc:#: Failure
-Value of: x
- Actual: 2
-Expected: 1
+ Expected: 1
+To be equal to: x
+ Which is: 2
[ FAILED ] FatalFailureTest.FatalFailureInSubroutine (? ms)
[ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine
(expecting a failure that x should be 1)
gtest_output_test_.cc:#: Failure
-Value of: x
- Actual: 2
-Expected: 1
+ Expected: 1
+To be equal to: x
+ Which is: 2
[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine (? ms)
[ RUN ] FatalFailureTest.NonfatalFailureInSubroutine
(expecting a failure on false)
diff --git a/test/gtest_premature_exit_test.cc b/test/gtest_premature_exit_test.cc
index f6b6be9..3b4dc7d 100644
--- a/test/gtest_premature_exit_test.cc
+++ b/test/gtest_premature_exit_test.cc
@@ -44,10 +44,6 @@ using ::testing::internal::posix::StatStruct;
namespace {
-// Is the TEST_PREMATURE_EXIT_FILE environment variable expected to be
-// set?
-const bool kTestPrematureExitFileEnvVarShouldBeSet = false;
-
class PrematureExitTest : public Test {
public:
// Returns true iff the given file exists.
@@ -97,16 +93,6 @@ TEST_F(PrematureExitDeathTest, FileExistsDuringExecutionOfDeathTest) {
}, "");
}
-// Tests that TEST_PREMATURE_EXIT_FILE is set where it's expected to
-// be set.
-TEST_F(PrematureExitTest, TestPrematureExitFileEnvVarIsSet) {
- if (kTestPrematureExitFileEnvVarShouldBeSet) {
- const char* const filepath = GetEnv("TEST_PREMATURE_EXIT_FILE");
- ASSERT_TRUE(filepath != NULL);
- ASSERT_NE(*filepath, '\0');
- }
-}
-
// Tests that the premature-exit file exists during the execution of a
// normal (non-death) test.
TEST_F(PrematureExitTest, PrematureExitFileExistsDuringTestExecution) {
diff --git a/test/gtest_test_utils.py b/test/gtest_test_utils.py
index 28884bd..4acd36c 100755
--- a/test/gtest_test_utils.py
+++ b/test/gtest_test_utils.py
@@ -175,10 +175,10 @@ def GetTestExecutablePath(executable_name, build_dir=None):
if not os.path.exists(path):
message = (
- 'Unable to find the test binary. Please make sure to provide path\n'
- 'to the binary via the --build_dir flag or the BUILD_DIR\n'
- 'environment variable.')
- print >> sys.stderr, message
+ 'Unable to find the test binary "%s". Please make sure to provide\n'
+ 'a path to the binary via the --build_dir flag or the BUILD_DIR\n'
+ 'environment variable.' % path)
+ sys.stdout.write(message)
sys.exit(1)
return path
diff --git a/test/gtest_throw_on_failure_test.py b/test/gtest_throw_on_failure_test.py
index 5678ffe..3e7740c 100755
--- a/test/gtest_throw_on_failure_test.py
+++ b/test/gtest_throw_on_failure_test.py
@@ -70,7 +70,7 @@ def SetEnvVar(env_var, value):
def Run(command):
"""Runs a command; returns True/False if its exit code is/isn't 0."""
- print 'Running "%s". . .' % ' '.join(command)
+ print('Running "%s". . .' % ' '.join(command))
p = gtest_test_utils.Subprocess(command)
return p.exited and p.exit_code == 0
diff --git a/test/gtest_uninitialized_test.py b/test/gtest_uninitialized_test.py
index 6ae57ee..4358370 100755
--- a/test/gtest_uninitialized_test.py
+++ b/test/gtest_uninitialized_test.py
@@ -46,8 +46,8 @@ def Assert(condition):
def AssertEq(expected, actual):
if expected != actual:
- print 'Expected: %s' % (expected,)
- print ' Actual: %s' % (actual,)
+ print('Expected: %s' % (expected,))
+ print(' Actual: %s' % (actual,))
raise AssertionError
diff --git a/test/gtest_unittest.cc b/test/gtest_unittest.cc
index 0cab07d..88e9413 100644
--- a/test/gtest_unittest.cc
+++ b/test/gtest_unittest.cc
@@ -94,7 +94,8 @@ class StreamingListenerTest : public Test {
StreamingListenerTest()
: fake_sock_writer_(new FakeSocketWriter),
streamer_(fake_sock_writer_),
- test_info_obj_("FooTest", "Bar", NULL, NULL, 0, NULL) {}
+ test_info_obj_("FooTest", "Bar", NULL, NULL,
+ CodeLocation(__FILE__, __LINE__), 0, NULL) {}
protected:
string* output() { return &(fake_sock_writer_->output_); }
@@ -233,7 +234,6 @@ using testing::TestProperty;
using testing::TestResult;
using testing::TimeInMillis;
using testing::UnitTest;
-using testing::kMaxStackTraceDepth;
using testing::internal::AddReference;
using testing::internal::AlwaysFalse;
using testing::internal::AlwaysTrue;
@@ -267,6 +267,8 @@ using testing::internal::IsContainerTest;
using testing::internal::IsNotContainer;
using testing::internal::NativeArray;
using testing::internal::ParseInt32Flag;
+using testing::internal::RelationToSourceCopy;
+using testing::internal::RelationToSourceReference;
using testing::internal::RemoveConst;
using testing::internal::RemoveReference;
using testing::internal::ShouldRunTestOnShard;
@@ -281,11 +283,12 @@ using testing::internal::TestEventListenersAccessor;
using testing::internal::TestResultAccessor;
using testing::internal::UInt32;
using testing::internal::WideStringToUtf8;
-using testing::internal::kCopy;
+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::kReference;
using testing::internal::kTestTypeIdInGoogleTest;
-using testing::internal::scoped_ptr;
+using testing::kMaxStackTraceDepth;
#if GTEST_HAS_STREAM_REDIRECTION
using testing::internal::CaptureStdout;
@@ -417,19 +420,11 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
private:
virtual void SetUp() {
saved_tz_ = NULL;
-#if _MSC_VER
-# pragma warning(push) // Saves the current warning state.
-# pragma warning(disable:4996) // Temporarily disables warning 4996
- // (function or variable may be unsafe
- // for getenv, function is deprecated for
- // strdup).
- if (getenv("TZ"))
- saved_tz_ = strdup(getenv("TZ"));
-# pragma warning(pop) // Restores the warning state again.
-#else
+
+ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* getenv, strdup: deprecated */)
if (getenv("TZ"))
saved_tz_ = strdup(getenv("TZ"));
-#endif
+ GTEST_DISABLE_MSC_WARNINGS_POP_()
// Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
// cannot use the local time zone because the function's output depends
@@ -453,11 +448,9 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
const std::string env_var =
std::string("TZ=") + (time_zone ? time_zone : "");
_putenv(env_var.c_str());
-# pragma warning(push) // Saves the current warning state.
-# pragma warning(disable:4996) // Temporarily disables warning 4996
- // (function is deprecated).
+ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
tzset();
-# pragma warning(pop) // Restores the warning state again.
+ GTEST_DISABLE_MSC_WARNINGS_POP_()
#else
if (time_zone) {
setenv(("TZ"), time_zone, 1);
@@ -1525,6 +1518,16 @@ TEST(TestResultPropertyTest, GetTestProperty) {
EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
}
+// Tests the Test class.
+//
+// It's difficult to test every public method of this class (we are
+// already stretching the limit of Google Test by using it to test itself!).
+// Fortunately, we don't have to do that, as we are already testing
+// the functionalities of the Test class extensively by using Google Test
+// alone.
+//
+// Therefore, this section only contains one test.
+
// Tests that GTestFlagSaver works on Windows and Mac.
class GTestFlagSaverTest : public Test {
@@ -1668,6 +1671,8 @@ TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
}
+# if !defined(GTEST_GET_INT32_FROM_ENV_)
+
// Tests that Int32FromGTestEnv() returns the default value when the
// environment variable overflows as an Int32.
TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
@@ -1692,6 +1697,8 @@ TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
}
+# endif // !defined(GTEST_GET_INT32_FROM_ENV_)
+
// Tests that Int32FromGTestEnv() parses and returns the value of the
// environment variable when it represents a valid decimal integer in
// the range of an Int32.
@@ -2459,7 +2466,7 @@ TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
ASSERT_STRCASEEQ("", "");
EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
- "(ignoring case)");
+ "Ignoring case");
}
// Tests ASSERT_STRCASENE.
@@ -3253,7 +3260,7 @@ TEST_F(SingleEvaluationTest, ASSERT_STR) {
// failed EXPECT_STRCASEEQ
EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
- "ignoring case");
+ "Ignoring case");
EXPECT_EQ(s1_ + 2, p1_);
EXPECT_EQ(s2_ + 2, p2_);
}
@@ -3441,6 +3448,79 @@ TEST_F(NoFatalFailureTest, MessageIsStreamable) {
// Tests non-string assertions.
+std::string EditsToString(const std::vector<EditType>& edits) {
+ std::string out;
+ for (size_t i = 0; i < edits.size(); ++i) {
+ static const char kEdits[] = " +-/";
+ out.append(1, kEdits[edits[i]]);
+ }
+ return out;
+}
+
+std::vector<size_t> CharsToIndices(const std::string& str) {
+ std::vector<size_t> out;
+ for (size_t i = 0; i < str.size(); ++i) {
+ out.push_back(str[i]);
+ }
+ return out;
+}
+
+std::vector<std::string> CharsToLines(const std::string& str) {
+ std::vector<std::string> out;
+ for (size_t i = 0; i < str.size(); ++i) {
+ out.push_back(str.substr(i, 1));
+ }
+ return out;
+}
+
+TEST(EditDistance, TestCases) {
+ struct Case {
+ int line;
+ const char* left;
+ const char* right;
+ const char* expected_edits;
+ const char* expected_diff;
+ };
+ static const Case kCases[] = {
+ // No change.
+ {__LINE__, "A", "A", " ", ""},
+ {__LINE__, "ABCDE", "ABCDE", " ", ""},
+ // Simple adds.
+ {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
+ {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
+ // Simple removes.
+ {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
+ {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
+ // Simple replaces.
+ {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
+ {__LINE__, "ABCD", "abcd", "////",
+ "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
+ // Path finding.
+ {__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +",
+ "@@ -1,8 +1,7 @@\n A\n B\n-C\n-D\n+X\n E\n-F\n G\n H\n+1\n"},
+ {__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ",
+ "@@ -1,9 +1,9 @@\n-A\n A\n-A\n+B\n A\n B\n C\n+D\n C\n-C\n+D\n C\n"},
+ {__LINE__, "ABCDE", "BCDCD", "- +/",
+ "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
+ {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++",
+ "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
+ "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
+ {}};
+ for (const Case* c = kCases; c->left; ++c) {
+ EXPECT_TRUE(c->expected_edits ==
+ EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
+ CharsToIndices(c->right))))
+ << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
+ << EditsToString(CalculateOptimalEdits(
+ CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
+ EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
+ CharsToLines(c->right)))
+ << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
+ << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
+ << ">";
+ }
+}
+
// Tests EqFailure(), used for implementing *EQ* assertions.
TEST(AssertionTest, EqFailure) {
const std::string foo_val("5"), bar_val("6");
@@ -3448,35 +3528,35 @@ TEST(AssertionTest, EqFailure) {
EqFailure("foo", "bar", foo_val, bar_val, false)
.failure_message());
EXPECT_STREQ(
- "Value of: bar\n"
- " Actual: 6\n"
- "Expected: foo\n"
- "Which is: 5",
+ " Expected: foo\n"
+ " Which is: 5\n"
+ "To be equal to: bar\n"
+ " Which is: 6",
msg1.c_str());
const std::string msg2(
EqFailure("foo", "6", foo_val, bar_val, false)
.failure_message());
EXPECT_STREQ(
- "Value of: 6\n"
- "Expected: foo\n"
- "Which is: 5",
+ " Expected: foo\n"
+ " Which is: 5\n"
+ "To be equal to: 6",
msg2.c_str());
const std::string msg3(
EqFailure("5", "bar", foo_val, bar_val, false)
.failure_message());
EXPECT_STREQ(
- "Value of: bar\n"
- " Actual: 6\n"
- "Expected: 5",
+ " Expected: 5\n"
+ "To be equal to: bar\n"
+ " Which is: 6",
msg3.c_str());
const std::string msg4(
EqFailure("5", "6", foo_val, bar_val, false).failure_message());
EXPECT_STREQ(
- "Value of: 6\n"
- "Expected: 5",
+ " Expected: 5\n"
+ "To be equal to: 6",
msg4.c_str());
const std::string msg5(
@@ -3484,13 +3564,32 @@ TEST(AssertionTest, EqFailure) {
std::string("\"x\""), std::string("\"y\""),
true).failure_message());
EXPECT_STREQ(
- "Value of: bar\n"
- " Actual: \"y\"\n"
- "Expected: foo (ignoring case)\n"
- "Which is: \"x\"",
+ " Expected: foo\n"
+ " Which is: \"x\"\n"
+ "To be equal to: bar\n"
+ " Which is: \"y\"\n"
+ "Ignoring case",
msg5.c_str());
}
+TEST(AssertionTest, EqFailureWithDiff) {
+ const std::string left(
+ "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
+ const std::string right(
+ "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
+ const std::string msg1(
+ EqFailure("left", "right", left, right, false).failure_message());
+ EXPECT_STREQ(
+ " Expected: left\n"
+ " Which is: "
+ "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
+ "To be equal to: right\n"
+ " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
+ "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
+ "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
+ msg1.c_str());
+}
+
// Tests AppendUserMessage(), used for implementing the *EQ* macros.
TEST(AssertionTest, AppendUserMessage) {
const std::string foo("foo");
@@ -3580,9 +3679,9 @@ TEST(ExpectTest, ASSERT_EQ_Double) {
TEST(AssertionTest, ASSERT_EQ) {
ASSERT_EQ(5, 2 + 3);
EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
- "Value of: 2*3\n"
- " Actual: 6\n"
- "Expected: 5");
+ " Expected: 5\n"
+ "To be equal to: 2*3\n"
+ " Which is: 6");
}
// Tests ASSERT_EQ(NULL, pointer).
@@ -3599,7 +3698,7 @@ TEST(AssertionTest, ASSERT_EQ_NULL) {
// A failure.
static int n = 0;
EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n),
- "Value of: &n\n");
+ "To be equal to: &n\n");
}
#endif // GTEST_CAN_COMPARE_NULL
@@ -3714,7 +3813,7 @@ void TestEq1(int x) {
// Tests calling a test subroutine that's not part of a fixture.
TEST(AssertionTest, NonFixtureSubroutine) {
EXPECT_FATAL_FAILURE(TestEq1(2),
- "Value of: x");
+ "To be equal to: x");
}
// An uncopyable class.
@@ -3763,7 +3862,7 @@ TEST(AssertionTest, AssertWorksWithUncopyableObject) {
EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
"IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
- "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
+ "Expected: x\n Which is: 5\nTo be equal to: y\n Which is: -1");
}
// Tests that uncopyable objects can be used in expects.
@@ -3775,7 +3874,7 @@ TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
"IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
EXPECT_EQ(x, x);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
- "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5");
+ "Expected: x\n Which is: 5\nTo be equal to: y\n Which is: -1");
}
enum NamedEnum {
@@ -3787,7 +3886,7 @@ TEST(AssertionTest, NamedEnum) {
EXPECT_EQ(kE1, kE1);
EXPECT_LT(kE1, kE2);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
- EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Actual: 1");
+ EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
}
// The version of gcc used in XCode 2.2 has a bug and doesn't allow
@@ -3851,9 +3950,9 @@ TEST(AssertionTest, AnonymousEnum) {
// ICE's in C++Builder.
EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
- "Value of: kCaseB");
+ "To be equal to: kCaseB");
EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
- "Actual: 42");
+ "Which is: 42");
# endif
EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
@@ -4291,9 +4390,9 @@ TEST(ExpectTest, ExpectFalseWithAssertionResult) {
TEST(ExpectTest, EXPECT_EQ) {
EXPECT_EQ(5, 2 + 3);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
- "Value of: 2*3\n"
- " Actual: 6\n"
- "Expected: 5");
+ " Expected: 5\n"
+ "To be equal to: 2*3\n"
+ " Which is: 6");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
"2 - 3");
}
@@ -4324,7 +4423,7 @@ TEST(ExpectTest, EXPECT_EQ_NULL) {
// A failure.
int n = 0;
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n),
- "Value of: &n\n");
+ "To be equal to: &n\n");
}
#endif // GTEST_CAN_COMPARE_NULL
@@ -4440,7 +4539,7 @@ TEST(ExpectTest, EXPECT_ANY_THROW) {
TEST(ExpectTest, ExpectPrecedence) {
EXPECT_EQ(1 < 2, true);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
- "Value of: true && false");
+ "To be equal to: true && false");
}
@@ -4587,7 +4686,7 @@ TEST(EqAssertionTest, Bool) {
EXPECT_FATAL_FAILURE({
bool false_value = false;
ASSERT_EQ(false_value, true);
- }, "Value of: true");
+ }, "To be equal to: true");
}
// Tests using int values in {EXPECT|ASSERT}_EQ.
@@ -4621,10 +4720,10 @@ TEST(EqAssertionTest, WideChar) {
EXPECT_EQ(L'b', L'b');
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
- "Value of: L'x'\n"
- " Actual: L'x' (120, 0x78)\n"
- "Expected: L'\0'\n"
- "Which is: L'\0' (0, 0x0)");
+ " Expected: L'\0'\n"
+ " Which is: L'\0' (0, 0x0)\n"
+ "To be equal to: L'x'\n"
+ " Which is: L'x' (120, 0x78)");
static wchar_t wchar;
wchar = L'b';
@@ -4632,7 +4731,7 @@ TEST(EqAssertionTest, WideChar) {
"wchar");
wchar = 0x8119;
EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
- "Value of: wchar");
+ "To be equal to: wchar");
}
// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
@@ -4661,8 +4760,8 @@ TEST(EqAssertionTest, StdString) {
static ::std::string str3(str1);
str3.at(2) = '\0';
EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
- "Value of: str3\n"
- " Actual: \"A \\0 in the middle\"");
+ "To be equal to: str3\n"
+ " Which is: \"A \\0 in the middle\"");
}
#if GTEST_HAS_STD_WSTRING
@@ -4782,7 +4881,7 @@ TEST(EqAssertionTest, CharPointer) {
ASSERT_EQ(p1, p1);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
- "Value of: p2");
+ "To be equal to: p2");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
"p2");
EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
@@ -4804,7 +4903,7 @@ TEST(EqAssertionTest, WideCharPointer) {
EXPECT_EQ(p0, p0);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
- "Value of: p2");
+ "To be equal to: p2");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
"p2");
void* pv3 = (void*)0x1234; // NOLINT
@@ -5026,6 +5125,31 @@ TEST(AssertionResultTest, CanStreamOstreamManipulators) {
EXPECT_STREQ("Data\n\\0Will be visible", r.message());
}
+// The next test uses explicit conversion operators -- a C++11 feature.
+#if GTEST_LANG_CXX11
+
+TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
+ struct ExplicitlyConvertibleToBool {
+ explicit operator bool() const { return value; }
+ bool value;
+ };
+ ExplicitlyConvertibleToBool v1 = {false};
+ ExplicitlyConvertibleToBool v2 = {true};
+ EXPECT_FALSE(v1);
+ EXPECT_TRUE(v2);
+}
+
+#endif // GTEST_LANG_CXX11
+
+struct ConvertibleToAssertionResult {
+ operator AssertionResult() const { return AssertionResult(true); }
+};
+
+TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
+ ConvertibleToAssertionResult obj;
+ EXPECT_TRUE(obj);
+}
+
// Tests streaming a user type whose definition and operator << are
// both in the global namespace.
class Base {
@@ -5210,6 +5334,59 @@ TEST_F(TestInfoTest, result) {
ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
}
+#define VERIFY_CODE_LOCATION \
+ const int expected_line = __LINE__ - 1; \
+ const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
+ ASSERT_TRUE(test_info); \
+ EXPECT_STREQ(__FILE__, test_info->file()); \
+ EXPECT_EQ(expected_line, test_info->line())
+
+TEST(CodeLocationForTEST, Verify) {
+ VERIFY_CODE_LOCATION;
+}
+
+class CodeLocationForTESTF : public Test {
+};
+
+TEST_F(CodeLocationForTESTF, Verify) {
+ VERIFY_CODE_LOCATION;
+}
+
+class CodeLocationForTESTP : public TestWithParam<int> {
+};
+
+TEST_P(CodeLocationForTESTP, Verify) {
+ VERIFY_CODE_LOCATION;
+}
+
+INSTANTIATE_TEST_CASE_P(, CodeLocationForTESTP, Values(0));
+
+template <typename T>
+class CodeLocationForTYPEDTEST : public Test {
+};
+
+TYPED_TEST_CASE(CodeLocationForTYPEDTEST, int);
+
+TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
+ VERIFY_CODE_LOCATION;
+}
+
+template <typename T>
+class CodeLocationForTYPEDTESTP : public Test {
+};
+
+TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP);
+
+TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
+ VERIFY_CODE_LOCATION;
+}
+
+REGISTER_TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP, Verify);
+
+INSTANTIATE_TYPED_TEST_CASE_P(My, CodeLocationForTYPEDTESTP, int);
+
+#undef VERIFY_CODE_LOCATION
+
// Tests setting up and tearing down a test case.
class SetUpTestCaseTest : public Test {
@@ -6225,7 +6402,108 @@ TEST_F(InitGoogleTestTest, WideStrings) {
GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
}
-#endif // GTEST_OS_WINDOWS
+# endif // GTEST_OS_WINDOWS
+
+#if GTEST_USE_OWN_FLAGFILE_FLAG_
+class FlagfileTest : public InitGoogleTestTest {
+ public:
+ virtual void SetUp() {
+ InitGoogleTestTest::SetUp();
+
+ testdata_path_.Set(internal::FilePath(
+ internal::TempDir() + internal::GetCurrentExecutableName().string() +
+ "_flagfile_test"));
+ testing::internal::posix::RmDir(testdata_path_.c_str());
+ EXPECT_TRUE(testdata_path_.CreateFolder());
+ }
+
+ virtual void TearDown() {
+ testing::internal::posix::RmDir(testdata_path_.c_str());
+ InitGoogleTestTest::TearDown();
+ }
+
+ internal::FilePath CreateFlagfile(const char* contents) {
+ internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
+ testdata_path_, internal::FilePath("unique"), "txt"));
+ FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
+ fprintf(f, "%s", contents);
+ fclose(f);
+ return file_path;
+ }
+
+ private:
+ internal::FilePath testdata_path_;
+};
+
+// Tests an empty flagfile.
+TEST_F(FlagfileTest, Empty) {
+ internal::FilePath flagfile_path(CreateFlagfile(""));
+ std::string flagfile_flag =
+ std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
+
+ const char* argv[] = {
+ "foo.exe",
+ flagfile_flag.c_str(),
+ NULL
+ };
+
+ const char* argv2[] = {
+ "foo.exe",
+ NULL
+ };
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
+}
+
+// Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
+TEST_F(FlagfileTest, FilterNonEmpty) {
+ internal::FilePath flagfile_path(CreateFlagfile(
+ "--" GTEST_FLAG_PREFIX_ "filter=abc"));
+ std::string flagfile_flag =
+ std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
+
+ const char* argv[] = {
+ "foo.exe",
+ flagfile_flag.c_str(),
+ NULL
+ };
+
+ const char* argv2[] = {
+ "foo.exe",
+ NULL
+ };
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
+}
+
+// Tests passing several flags via --gtest_flagfile.
+TEST_F(FlagfileTest, SeveralFlags) {
+ internal::FilePath flagfile_path(CreateFlagfile(
+ "--" GTEST_FLAG_PREFIX_ "filter=abc\n"
+ "--" GTEST_FLAG_PREFIX_ "break_on_failure\n"
+ "--" GTEST_FLAG_PREFIX_ "list_tests"));
+ std::string flagfile_flag =
+ std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
+
+ const char* argv[] = {
+ "foo.exe",
+ flagfile_flag.c_str(),
+ NULL
+ };
+
+ const char* argv2[] = {
+ "foo.exe",
+ NULL
+ };
+
+ Flags expected_flags;
+ expected_flags.break_on_failure = true;
+ expected_flags.filter = "abc";
+ expected_flags.list_tests = true;
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
+}
+#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
// Tests current_test_info() in UnitTest.
class CurrentTestInfoTest : public Test {
@@ -6563,6 +6841,18 @@ TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
SetEnv("TERM", "screen-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
+ SetEnv("TERM", "tmux"); // TERM supports colors.
+ EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
+
+ SetEnv("TERM", "tmux-256color"); // TERM supports colors.
+ EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
+
+ SetEnv("TERM", "rxvt-unicode"); // TERM supports colors.
+ EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
+
+ SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors.
+ EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
+
SetEnv("TERM", "linux"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
@@ -7327,7 +7617,7 @@ TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
TEST(NativeArrayTest, ConstructorFromArrayWorks) {
const int a[3] = { 0, 1, 2 };
- NativeArray<int> na(a, 3, kReference);
+ NativeArray<int> na(a, 3, RelationToSourceReference());
EXPECT_EQ(3U, na.size());
EXPECT_EQ(a, na.begin());
}
@@ -7337,7 +7627,7 @@ TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
Array* a = new Array[1];
(*a)[0] = 0;
(*a)[1] = 1;
- NativeArray<int> na(*a, 2, kCopy);
+ NativeArray<int> na(*a, 2, RelationToSourceCopy());
EXPECT_NE(*a, na.begin());
delete[] a;
EXPECT_EQ(0, na.begin()[0]);
@@ -7357,7 +7647,7 @@ TEST(NativeArrayTest, TypeMembersAreCorrect) {
TEST(NativeArrayTest, MethodsWork) {
const int a[3] = { 0, 1, 2 };
- NativeArray<int> na(a, 3, kCopy);
+ NativeArray<int> na(a, 3, RelationToSourceCopy());
ASSERT_EQ(3U, na.size());
EXPECT_EQ(3, na.end() - na.begin());
@@ -7372,18 +7662,18 @@ TEST(NativeArrayTest, MethodsWork) {
EXPECT_TRUE(na == na);
- NativeArray<int> na2(a, 3, kReference);
+ NativeArray<int> na2(a, 3, RelationToSourceReference());
EXPECT_TRUE(na == na2);
const int b1[3] = { 0, 1, 1 };
const int b2[4] = { 0, 1, 2, 3 };
- EXPECT_FALSE(na == NativeArray<int>(b1, 3, kReference));
- EXPECT_FALSE(na == NativeArray<int>(b2, 4, kCopy));
+ EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
+ EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
}
TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
const char a[2][3] = { "hi", "lo" };
- NativeArray<char[3]> na(a, 2, kReference);
+ NativeArray<char[3]> na(a, 2, RelationToSourceReference());
ASSERT_EQ(2U, na.size());
EXPECT_EQ(a, na.begin());
}
@@ -7413,3 +7703,4 @@ TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
EXPECT_FALSE(SkipPrefix("world!", &p));
EXPECT_EQ(str, p);
}
+
diff --git a/test/gtest_xml_output_unittest.py b/test/gtest_xml_output_unittest.py
index f605d4e..bcd5975 100755
--- a/test/gtest_xml_output_unittest.py
+++ b/test/gtest_xml_output_unittest.py
@@ -64,20 +64,20 @@ EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
</testsuite>
<testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*">
<testcase name="Fails" status="run" time="*" classname="FailedTest">
- <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 2&#x0A;Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
-Value of: 2
-Expected: 1%(stack)s]]></failure>
+ <failure message="gtest_xml_output_unittest_.cc:*&#x0A; Expected: 1&#x0A;To be equal to: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
+ Expected: 1
+To be equal to: 2%(stack)s]]></failure>
</testcase>
</testsuite>
<testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*">
<testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/>
<testcase name="Fails" status="run" time="*" classname="MixedResultTest">
- <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 2&#x0A;Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
-Value of: 2
-Expected: 1%(stack)s]]></failure>
- <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 3&#x0A;Expected: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
-Value of: 3
-Expected: 2%(stack)s]]></failure>
+ <failure message="gtest_xml_output_unittest_.cc:*&#x0A; Expected: 1&#x0A;To be equal to: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
+ Expected: 1
+To be equal to: 2%(stack)s]]></failure>
+ <failure message="gtest_xml_output_unittest_.cc:*&#x0A; Expected: 2&#x0A;To be equal to: 3" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
+ Expected: 2
+To be equal to: 3%(stack)s]]></failure>
</testcase>
<testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/>
</testsuite>
@@ -209,7 +209,8 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
'gtest_no_test_unittest')
try:
os.remove(output_file)
- except OSError, e:
+ except OSError:
+ e = sys.exc_info()[1]
if e.errno != errno.ENOENT:
raise
diff --git a/test/gtest_xml_test_utils.py b/test/gtest_xml_test_utils.py
index 3d0c3b2..341956b 100755
--- a/test/gtest_xml_test_utils.py
+++ b/test/gtest_xml_test_utils.py
@@ -101,7 +101,7 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
self.assertEquals(
len(expected_children), len(actual_children),
'number of child elements differ in element ' + actual_node.tagName)
- for child_id, child in expected_children.iteritems():
+ for child_id, child in expected_children.items():
self.assert_(child_id in actual_children,
'<%s> is not in <%s> (in element %s)' %
(child_id, actual_children, actual_node.tagName))