From 421f527df32ff3f437166513d3621fd543bf42a7 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 16:23:20 -0400 Subject: more test changes --- googletest/test/BUILD.bazel | 6 +- googletest/test/googletest-message-test.cc | 159 +++ googletest/test/googletest-options-test.cc | 213 ++++ googletest/test/googletest-port-test.cc | 1303 ++++++++++++++++++++ googletest/test/googletest-printers-test.cc | 1737 +++++++++++++++++++++++++++ googletest/test/googletest-tuple-test.cc | 320 +++++ googletest/test/gtest-message_test.cc | 159 --- googletest/test/gtest-options_test.cc | 213 ---- googletest/test/gtest-port_test.cc | 1303 -------------------- googletest/test/gtest-printers_test.cc | 1737 --------------------------- googletest/test/gtest-tuple_test.cc | 320 ----- 11 files changed, 3735 insertions(+), 3735 deletions(-) create mode 100644 googletest/test/googletest-message-test.cc create mode 100644 googletest/test/googletest-options-test.cc create mode 100644 googletest/test/googletest-port-test.cc create mode 100644 googletest/test/googletest-printers-test.cc create mode 100644 googletest/test/googletest-tuple-test.cc delete mode 100644 googletest/test/gtest-message_test.cc delete mode 100644 googletest/test/gtest-options_test.cc delete mode 100644 googletest/test/gtest-port_test.cc delete mode 100644 googletest/test/gtest-printers_test.cc delete mode 100644 googletest/test/gtest-tuple_test.cc diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 7d0932b..a5c6b14 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -49,7 +49,7 @@ config_setting( values = {"define": "absl=1"}, ) -#on windows exclude gtest-tuple.h and gtest-tuple_test.cc +#on windows exclude gtest-tuple.h and googletest-tuple-test.cc cc_test( name = "gtest_all_test", size = "small", @@ -62,7 +62,7 @@ cc_test( ], exclude = [ "gtest-unittest-api_test.cc", - "gtest-tuple_test.cc", + "googletest-tuple-test.cc", "googletest/src/gtest-all.cc", "gtest_all_test.cc", "gtest-death-test_ex_test.cc", @@ -85,7 +85,7 @@ cc_test( "//:windows": [], "//:windows_msvc": [], "//conditions:default": [ - "gtest-tuple_test.cc", + "googletest-tuple-test.cc", ], }), copts = select({ diff --git a/googletest/test/googletest-message-test.cc b/googletest/test/googletest-message-test.cc new file mode 100644 index 0000000..175238e --- /dev/null +++ b/googletest/test/googletest-message-test.cc @@ -0,0 +1,159 @@ +// Copyright 2005, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// Tests for the Message class. + +#include "gtest/gtest-message.h" + +#include "gtest/gtest.h" + +namespace { + +using ::testing::Message; + +// Tests the testing::Message class + +// Tests the default constructor. +TEST(MessageTest, DefaultConstructor) { + const Message msg; + EXPECT_EQ("", msg.GetString()); +} + +// Tests the copy constructor. +TEST(MessageTest, CopyConstructor) { + const Message msg1("Hello"); + const Message msg2(msg1); + EXPECT_EQ("Hello", msg2.GetString()); +} + +// Tests constructing a Message from a C-string. +TEST(MessageTest, ConstructsFromCString) { + Message msg("Hello"); + EXPECT_EQ("Hello", msg.GetString()); +} + +// Tests streaming a float. +TEST(MessageTest, StreamsFloat) { + const std::string s = (Message() << 1.23456F << " " << 2.34567F).GetString(); + // Both numbers should be printed with enough precision. + EXPECT_PRED_FORMAT2(testing::IsSubstring, "1.234560", s.c_str()); + EXPECT_PRED_FORMAT2(testing::IsSubstring, " 2.345669", s.c_str()); +} + +// Tests streaming a double. +TEST(MessageTest, StreamsDouble) { + const std::string s = (Message() << 1260570880.4555497 << " " + << 1260572265.1954534).GetString(); + // Both numbers should be printed with enough precision. + EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str()); + EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str()); +} + +// Tests streaming a non-char pointer. +TEST(MessageTest, StreamsPointer) { + int n = 0; + int* p = &n; + EXPECT_NE("(null)", (Message() << p).GetString()); +} + +// Tests streaming a NULL non-char pointer. +TEST(MessageTest, StreamsNullPointer) { + int* p = NULL; + EXPECT_EQ("(null)", (Message() << p).GetString()); +} + +// Tests streaming a C string. +TEST(MessageTest, StreamsCString) { + EXPECT_EQ("Foo", (Message() << "Foo").GetString()); +} + +// Tests streaming a NULL C string. +TEST(MessageTest, StreamsNullCString) { + char* p = NULL; + EXPECT_EQ("(null)", (Message() << p).GetString()); +} + +// Tests streaming std::string. +TEST(MessageTest, StreamsString) { + const ::std::string str("Hello"); + EXPECT_EQ("Hello", (Message() << str).GetString()); +} + +// Tests that we can output strings containing embedded NULs. +TEST(MessageTest, StreamsStringWithEmbeddedNUL) { + const char char_array_with_nul[] = + "Here's a NUL\0 and some more string"; + const ::std::string string_with_nul(char_array_with_nul, + sizeof(char_array_with_nul) - 1); + EXPECT_EQ("Here's a NUL\\0 and some more string", + (Message() << string_with_nul).GetString()); +} + +// Tests streaming a NUL char. +TEST(MessageTest, StreamsNULChar) { + EXPECT_EQ("\\0", (Message() << '\0').GetString()); +} + +// Tests streaming int. +TEST(MessageTest, StreamsInt) { + EXPECT_EQ("123", (Message() << 123).GetString()); +} + +// Tests that basic IO manipulators (endl, ends, and flush) can be +// streamed to Message. +TEST(MessageTest, StreamsBasicIoManip) { + EXPECT_EQ("Line 1.\nA NUL char \\0 in line 2.", + (Message() << "Line 1." << std::endl + << "A NUL char " << std::ends << std::flush + << " in line 2.").GetString()); +} + +// Tests Message::GetString() +TEST(MessageTest, GetString) { + Message msg; + msg << 1 << " lamb"; + EXPECT_EQ("1 lamb", msg.GetString()); +} + +// Tests streaming a Message object to an ostream. +TEST(MessageTest, StreamsToOStream) { + Message msg("Hello"); + ::std::stringstream ss; + ss << msg; + EXPECT_EQ("Hello", testing::internal::StringStreamToString(&ss)); +} + +// Tests that a Message object doesn't take up too much stack space. +TEST(MessageTest, DoesNotTakeUpMuchStackSpace) { + EXPECT_LE(sizeof(Message), 16U); +} + +} // namespace diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc new file mode 100644 index 0000000..e4c0d04 --- /dev/null +++ b/googletest/test/googletest-options-test.cc @@ -0,0 +1,213 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// +// Google Test UnitTestOptions tests +// +// This file tests classes and functions used internally by +// Google Test. They are subject to change without notice. +// +// This file is #included from gtest.cc, to avoid changing build or +// make-files on Windows and other platforms. Do not #include this file +// anywhere else! + +#include "gtest/gtest.h" + +#if GTEST_OS_WINDOWS_MOBILE +# include +#elif GTEST_OS_WINDOWS +# include +#endif // GTEST_OS_WINDOWS_MOBILE + +#include "src/gtest-internal-inl.h" + +namespace testing { +namespace internal { +namespace { + +// Turns the given relative path into an absolute path. +FilePath GetAbsolutePathOf(const FilePath& relative_path) { + return FilePath::ConcatPaths(FilePath::GetCurrentDir(), relative_path); +} + +// Testing UnitTestOptions::GetOutputFormat/GetOutputFile. + +TEST(XmlOutputTest, GetOutputFormatDefault) { + GTEST_FLAG(output) = ""; + EXPECT_STREQ("", UnitTestOptions::GetOutputFormat().c_str()); +} + +TEST(XmlOutputTest, GetOutputFormat) { + GTEST_FLAG(output) = "xml:filename"; + EXPECT_STREQ("xml", UnitTestOptions::GetOutputFormat().c_str()); +} + +TEST(XmlOutputTest, GetOutputFileDefault) { + GTEST_FLAG(output) = ""; + EXPECT_EQ(GetAbsolutePathOf(FilePath("test_detail.xml")).string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +} + +TEST(XmlOutputTest, GetOutputFileSingleFile) { + GTEST_FLAG(output) = "xml:filename.abc"; + EXPECT_EQ(GetAbsolutePathOf(FilePath("filename.abc")).string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +} + +TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) { + GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_; + const std::string expected_output_file = + GetAbsolutePathOf( + FilePath(std::string("path") + GTEST_PATH_SEP_ + + GetCurrentExecutableName().string() + ".xml")).string(); + const std::string& output_file = + UnitTestOptions::GetAbsolutePathToOutputFile(); +#if GTEST_OS_WINDOWS + EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); +#else + EXPECT_EQ(expected_output_file, output_file.c_str()); +#endif +} + +TEST(OutputFileHelpersTest, GetCurrentExecutableName) { + const std::string exe_str = GetCurrentExecutableName().string(); +#if GTEST_OS_WINDOWS + const bool success = + _strcmpi("googletest-options-test", exe_str.c_str()) == 0 || + _strcmpi("gtest-options-ex_test", exe_str.c_str()) == 0 || + _strcmpi("gtest_all_test", exe_str.c_str()) == 0 || + _strcmpi("gtest_dll_test", exe_str.c_str()) == 0; +#elif GTEST_OS_FUCHSIA + const bool success = exe_str == "app"; +#else + // TODO(wan@google.com): remove the hard-coded "lt-" prefix when + // Chandler Carruth's libtool replacement is ready. + const bool success = + exe_str == "googletest-options-test" || + exe_str == "gtest_all_test" || + exe_str == "lt-gtest_all_test" || + exe_str == "gtest_dll_test"; +#endif // GTEST_OS_WINDOWS + if (!success) + FAIL() << "GetCurrentExecutableName() returns " << exe_str; +} + +#if !GTEST_OS_FUCHSIA + +class XmlOutputChangeDirTest : public Test { + protected: + virtual void SetUp() { + original_working_dir_ = FilePath::GetCurrentDir(); + posix::ChDir(".."); + // This will make the test fail if run from the root directory. + EXPECT_NE(original_working_dir_.string(), + FilePath::GetCurrentDir().string()); + } + + virtual void TearDown() { + posix::ChDir(original_working_dir_.string().c_str()); + } + + FilePath original_working_dir_; +}; + +TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) { + GTEST_FLAG(output) = ""; + EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, + FilePath("test_detail.xml")).string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +} + +TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) { + GTEST_FLAG(output) = "xml"; + EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, + FilePath("test_detail.xml")).string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +} + +TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) { + GTEST_FLAG(output) = "xml:filename.abc"; + EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, + FilePath("filename.abc")).string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +} + +TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { + GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_; + const std::string expected_output_file = + FilePath::ConcatPaths( + original_working_dir_, + FilePath(std::string("path") + GTEST_PATH_SEP_ + + GetCurrentExecutableName().string() + ".xml")).string(); + const std::string& output_file = + UnitTestOptions::GetAbsolutePathToOutputFile(); +#if GTEST_OS_WINDOWS + EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); +#else + EXPECT_EQ(expected_output_file, output_file.c_str()); +#endif +} + +TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) { +#if GTEST_OS_WINDOWS + GTEST_FLAG(output) = "xml:c:\\tmp\\filename.abc"; + EXPECT_EQ(FilePath("c:\\tmp\\filename.abc").string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +#else + GTEST_FLAG(output) ="xml:/tmp/filename.abc"; + EXPECT_EQ(FilePath("/tmp/filename.abc").string(), + UnitTestOptions::GetAbsolutePathToOutputFile()); +#endif +} + +TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) { +#if GTEST_OS_WINDOWS + const std::string path = "c:\\tmp\\"; +#else + const std::string path = "/tmp/"; +#endif + + GTEST_FLAG(output) = "xml:" + path; + const std::string expected_output_file = + path + GetCurrentExecutableName().string() + ".xml"; + const std::string& output_file = + UnitTestOptions::GetAbsolutePathToOutputFile(); + +#if GTEST_OS_WINDOWS + EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); +#else + EXPECT_EQ(expected_output_file, output_file.c_str()); +#endif +} + +#endif // !GTEST_OS_FUCHSIA + +} // namespace +} // namespace internal +} // namespace testing diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc new file mode 100644 index 0000000..15a629f --- /dev/null +++ b/googletest/test/googletest-port-test.cc @@ -0,0 +1,1303 @@ +// Copyright 2008, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Authors: vladl@google.com (Vlad Losev), wan@google.com (Zhanyong Wan) +// +// This file tests the internal cross-platform support utilities. + +#include "gtest/internal/gtest-port.h" + +#include + +#if GTEST_OS_MAC +# include +#endif // GTEST_OS_MAC + +#include +#include // For std::pair and std::make_pair. +#include + +#include "gtest/gtest.h" +#include "gtest/gtest-spi.h" +#include "src/gtest-internal-inl.h" + +using std::make_pair; +using std::pair; + +namespace testing { +namespace internal { + +TEST(IsXDigitTest, WorksForNarrowAscii) { + EXPECT_TRUE(IsXDigit('0')); + EXPECT_TRUE(IsXDigit('9')); + EXPECT_TRUE(IsXDigit('A')); + EXPECT_TRUE(IsXDigit('F')); + EXPECT_TRUE(IsXDigit('a')); + EXPECT_TRUE(IsXDigit('f')); + + EXPECT_FALSE(IsXDigit('-')); + EXPECT_FALSE(IsXDigit('g')); + EXPECT_FALSE(IsXDigit('G')); +} + +TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) { + EXPECT_FALSE(IsXDigit(static_cast('\x80'))); + EXPECT_FALSE(IsXDigit(static_cast('0' | '\x80'))); +} + +TEST(IsXDigitTest, WorksForWideAscii) { + EXPECT_TRUE(IsXDigit(L'0')); + EXPECT_TRUE(IsXDigit(L'9')); + EXPECT_TRUE(IsXDigit(L'A')); + EXPECT_TRUE(IsXDigit(L'F')); + EXPECT_TRUE(IsXDigit(L'a')); + EXPECT_TRUE(IsXDigit(L'f')); + + EXPECT_FALSE(IsXDigit(L'-')); + EXPECT_FALSE(IsXDigit(L'g')); + EXPECT_FALSE(IsXDigit(L'G')); +} + +TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) { + EXPECT_FALSE(IsXDigit(static_cast(0x80))); + EXPECT_FALSE(IsXDigit(static_cast(L'0' | 0x80))); + EXPECT_FALSE(IsXDigit(static_cast(L'0' | 0x100))); +} + +class Base { + public: + // Copy constructor and assignment operator do exactly what we need, so we + // use them. + Base() : member_(0) {} + explicit Base(int n) : member_(n) {} + virtual ~Base() {} + int member() { return member_; } + + private: + int member_; +}; + +class Derived : public Base { + public: + explicit Derived(int n) : Base(n) {} +}; + +TEST(ImplicitCastTest, ConvertsPointers) { + Derived derived(0); + EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_(&derived)); +} + +TEST(ImplicitCastTest, CanUseInheritance) { + Derived derived(1); + Base base = ::testing::internal::ImplicitCast_(derived); + EXPECT_EQ(derived.member(), base.member()); +} + +class Castable { + public: + explicit Castable(bool* converted) : converted_(converted) {} + operator Base() { + *converted_ = true; + return Base(); + } + + private: + bool* converted_; +}; + +TEST(ImplicitCastTest, CanUseNonConstCastOperator) { + bool converted = false; + Castable castable(&converted); + Base base = ::testing::internal::ImplicitCast_(castable); + EXPECT_TRUE(converted); +} + +class ConstCastable { + public: + explicit ConstCastable(bool* converted) : converted_(converted) {} + operator Base() const { + *converted_ = true; + return Base(); + } + + private: + bool* converted_; +}; + +TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) { + bool converted = false; + const ConstCastable const_castable(&converted); + Base base = ::testing::internal::ImplicitCast_(const_castable); + EXPECT_TRUE(converted); +} + +class ConstAndNonConstCastable { + public: + ConstAndNonConstCastable(bool* converted, bool* const_converted) + : converted_(converted), const_converted_(const_converted) {} + operator Base() { + *converted_ = true; + return Base(); + } + operator Base() const { + *const_converted_ = true; + return Base(); + } + + private: + bool* converted_; + bool* const_converted_; +}; + +TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) { + bool converted = false; + bool const_converted = false; + ConstAndNonConstCastable castable(&converted, &const_converted); + Base base = ::testing::internal::ImplicitCast_(castable); + EXPECT_TRUE(converted); + EXPECT_FALSE(const_converted); + + converted = false; + const_converted = false; + const ConstAndNonConstCastable const_castable(&converted, &const_converted); + base = ::testing::internal::ImplicitCast_(const_castable); + EXPECT_FALSE(converted); + EXPECT_TRUE(const_converted); +} + +class To { + public: + To(bool* converted) { *converted = true; } // NOLINT +}; + +TEST(ImplicitCastTest, CanUseImplicitConstructor) { + bool converted = false; + To to = ::testing::internal::ImplicitCast_(&converted); + (void)to; + EXPECT_TRUE(converted); +} + +TEST(IteratorTraitsTest, WorksForSTLContainerIterators) { + StaticAssertTypeEq::const_iterator>::value_type>(); + StaticAssertTypeEq::iterator>::value_type>(); +} + +TEST(IteratorTraitsTest, WorksForPointerToNonConst) { + StaticAssertTypeEq::value_type>(); + StaticAssertTypeEq::value_type>(); +} + +TEST(IteratorTraitsTest, WorksForPointerToConst) { + StaticAssertTypeEq::value_type>(); + StaticAssertTypeEq::value_type>(); +} + +// Tests that the element_type typedef is available in scoped_ptr and refers +// to the parameter type. +TEST(ScopedPtrTest, DefinesElementType) { + StaticAssertTypeEq::element_type>(); +} + +// TODO(vladl@google.com): Implement THE REST of scoped_ptr tests. + +TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) { + if (AlwaysFalse()) + GTEST_CHECK_(false) << "This should never be executed; " + "It's a compilation test only."; + + if (AlwaysTrue()) + GTEST_CHECK_(true); + else + ; // NOLINT + + if (AlwaysFalse()) + ; // NOLINT + else + GTEST_CHECK_(true) << ""; +} + +TEST(GtestCheckSyntaxTest, WorksWithSwitch) { + switch (0) { + case 1: + break; + default: + GTEST_CHECK_(true); + } + + switch (0) + case 0: + GTEST_CHECK_(true) << "Check failed in switch case"; +} + +// Verifies behavior of FormatFileLocation. +TEST(FormatFileLocationTest, FormatsFileLocation) { + EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42)); + EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42)); +} + +TEST(FormatFileLocationTest, FormatsUnknownFile) { + EXPECT_PRED_FORMAT2( + IsSubstring, "unknown file", FormatFileLocation(NULL, 42)); + EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(NULL, 42)); +} + +TEST(FormatFileLocationTest, FormatsUknownLine) { + EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1)); +} + +TEST(FormatFileLocationTest, FormatsUknownFileAndLine) { + EXPECT_EQ("unknown file:", FormatFileLocation(NULL, -1)); +} + +// Verifies behavior of FormatCompilerIndependentFileLocation. +TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) { + EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42)); +} + +TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) { + EXPECT_EQ("unknown file:42", + FormatCompilerIndependentFileLocation(NULL, 42)); +} + +TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) { + EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1)); +} + +TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) { + EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1)); +} + +#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA +void* ThreadFunc(void* data) { + internal::Mutex* mutex = static_cast(data); + mutex->Lock(); + mutex->Unlock(); + return NULL; +} + +TEST(GetThreadCountTest, ReturnsCorrectValue) { + const size_t starting_count = GetThreadCount(); + pthread_t thread_id; + + internal::Mutex mutex; + { + internal::MutexLock lock(&mutex); + pthread_attr_t attr; + ASSERT_EQ(0, pthread_attr_init(&attr)); + ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); + + const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex); + ASSERT_EQ(0, pthread_attr_destroy(&attr)); + ASSERT_EQ(0, status); + EXPECT_EQ(starting_count + 1, GetThreadCount()); + } + + void* dummy; + ASSERT_EQ(0, pthread_join(thread_id, &dummy)); + + // The OS may not immediately report the updated thread count after + // joining a thread, causing flakiness in this test. To counter that, we + // wait for up to .5 seconds for the OS to report the correct value. + for (int i = 0; i < 5; ++i) { + if (GetThreadCount() == starting_count) + break; + + SleepMilliseconds(100); + } + + EXPECT_EQ(starting_count, GetThreadCount()); +} +#else +TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) { + EXPECT_EQ(0U, GetThreadCount()); +} +#endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA + +TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { + const bool a_false_condition = false; + const char regex[] = +#ifdef _MSC_VER + "googletest-port-test\\.cc\\(\\d+\\):" +#elif GTEST_USES_POSIX_RE + "googletest-port-test\\.cc:[0-9]+" +#else + "googletest-port-test\\.cc:\\d+" +#endif // _MSC_VER + ".*a_false_condition.*Extra info.*"; + + EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info", + regex); +} + +#if GTEST_HAS_DEATH_TEST + +TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { + EXPECT_EXIT({ + GTEST_CHECK_(true) << "Extra info"; + ::std::cerr << "Success\n"; + exit(0); }, + ::testing::ExitedWithCode(0), "Success"); +} + +#endif // GTEST_HAS_DEATH_TEST + +// Verifies that Google Test choose regular expression engine appropriate to +// the platform. The test will produce compiler errors in case of failure. +// For simplicity, we only cover the most important platforms here. +TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) { +#if !GTEST_USES_PCRE +# if GTEST_HAS_POSIX_RE + + EXPECT_TRUE(GTEST_USES_POSIX_RE); + +# else + + EXPECT_TRUE(GTEST_USES_SIMPLE_RE); + +# endif +#endif // !GTEST_USES_PCRE +} + +#if GTEST_USES_POSIX_RE + +# if GTEST_HAS_TYPED_TEST + +template +class RETest : public ::testing::Test {}; + +// Defines StringTypes as the list of all string types that class RE +// supports. +typedef testing::Types< + ::std::string, +# if GTEST_HAS_GLOBAL_STRING + ::string, +# endif // GTEST_HAS_GLOBAL_STRING + const char*> StringTypes; + +TYPED_TEST_CASE(RETest, StringTypes); + +// Tests RE's implicit constructors. +TYPED_TEST(RETest, ImplicitConstructorWorks) { + const RE empty(TypeParam("")); + EXPECT_STREQ("", empty.pattern()); + + const RE simple(TypeParam("hello")); + EXPECT_STREQ("hello", simple.pattern()); + + const RE normal(TypeParam(".*(\\w+)")); + EXPECT_STREQ(".*(\\w+)", normal.pattern()); +} + +// Tests that RE's constructors reject invalid regular expressions. +TYPED_TEST(RETest, RejectsInvalidRegex) { + EXPECT_NONFATAL_FAILURE({ + const RE invalid(TypeParam("?")); + }, "\"?\" is not a valid POSIX Extended regular expression."); +} + +// Tests RE::FullMatch(). +TYPED_TEST(RETest, FullMatchWorks) { + const RE empty(TypeParam("")); + EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty)); + EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty)); + + const RE re(TypeParam("a.*z")); + EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re)); + EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re)); + EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re)); + EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re)); +} + +// Tests RE::PartialMatch(). +TYPED_TEST(RETest, PartialMatchWorks) { + const RE empty(TypeParam("")); + EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty)); + EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty)); + + const RE re(TypeParam("a.*z")); + EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re)); + EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re)); + EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re)); + EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re)); + EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re)); +} + +# endif // GTEST_HAS_TYPED_TEST + +#elif GTEST_USES_SIMPLE_RE + +TEST(IsInSetTest, NulCharIsNotInAnySet) { + EXPECT_FALSE(IsInSet('\0', "")); + EXPECT_FALSE(IsInSet('\0', "\0")); + EXPECT_FALSE(IsInSet('\0', "a")); +} + +TEST(IsInSetTest, WorksForNonNulChars) { + EXPECT_FALSE(IsInSet('a', "Ab")); + EXPECT_FALSE(IsInSet('c', "")); + + EXPECT_TRUE(IsInSet('b', "bcd")); + EXPECT_TRUE(IsInSet('b', "ab")); +} + +TEST(IsAsciiDigitTest, IsFalseForNonDigit) { + EXPECT_FALSE(IsAsciiDigit('\0')); + EXPECT_FALSE(IsAsciiDigit(' ')); + EXPECT_FALSE(IsAsciiDigit('+')); + EXPECT_FALSE(IsAsciiDigit('-')); + EXPECT_FALSE(IsAsciiDigit('.')); + EXPECT_FALSE(IsAsciiDigit('a')); +} + +TEST(IsAsciiDigitTest, IsTrueForDigit) { + EXPECT_TRUE(IsAsciiDigit('0')); + EXPECT_TRUE(IsAsciiDigit('1')); + EXPECT_TRUE(IsAsciiDigit('5')); + EXPECT_TRUE(IsAsciiDigit('9')); +} + +TEST(IsAsciiPunctTest, IsFalseForNonPunct) { + EXPECT_FALSE(IsAsciiPunct('\0')); + EXPECT_FALSE(IsAsciiPunct(' ')); + EXPECT_FALSE(IsAsciiPunct('\n')); + EXPECT_FALSE(IsAsciiPunct('a')); + EXPECT_FALSE(IsAsciiPunct('0')); +} + +TEST(IsAsciiPunctTest, IsTrueForPunct) { + for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) { + EXPECT_PRED1(IsAsciiPunct, *p); + } +} + +TEST(IsRepeatTest, IsFalseForNonRepeatChar) { + EXPECT_FALSE(IsRepeat('\0')); + EXPECT_FALSE(IsRepeat(' ')); + EXPECT_FALSE(IsRepeat('a')); + EXPECT_FALSE(IsRepeat('1')); + EXPECT_FALSE(IsRepeat('-')); +} + +TEST(IsRepeatTest, IsTrueForRepeatChar) { + EXPECT_TRUE(IsRepeat('?')); + EXPECT_TRUE(IsRepeat('*')); + EXPECT_TRUE(IsRepeat('+')); +} + +TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) { + EXPECT_FALSE(IsAsciiWhiteSpace('\0')); + EXPECT_FALSE(IsAsciiWhiteSpace('a')); + EXPECT_FALSE(IsAsciiWhiteSpace('1')); + EXPECT_FALSE(IsAsciiWhiteSpace('+')); + EXPECT_FALSE(IsAsciiWhiteSpace('_')); +} + +TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) { + EXPECT_TRUE(IsAsciiWhiteSpace(' ')); + EXPECT_TRUE(IsAsciiWhiteSpace('\n')); + EXPECT_TRUE(IsAsciiWhiteSpace('\r')); + EXPECT_TRUE(IsAsciiWhiteSpace('\t')); + EXPECT_TRUE(IsAsciiWhiteSpace('\v')); + EXPECT_TRUE(IsAsciiWhiteSpace('\f')); +} + +TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) { + EXPECT_FALSE(IsAsciiWordChar('\0')); + EXPECT_FALSE(IsAsciiWordChar('+')); + EXPECT_FALSE(IsAsciiWordChar('.')); + EXPECT_FALSE(IsAsciiWordChar(' ')); + EXPECT_FALSE(IsAsciiWordChar('\n')); +} + +TEST(IsAsciiWordCharTest, IsTrueForLetter) { + EXPECT_TRUE(IsAsciiWordChar('a')); + EXPECT_TRUE(IsAsciiWordChar('b')); + EXPECT_TRUE(IsAsciiWordChar('A')); + EXPECT_TRUE(IsAsciiWordChar('Z')); +} + +TEST(IsAsciiWordCharTest, IsTrueForDigit) { + EXPECT_TRUE(IsAsciiWordChar('0')); + EXPECT_TRUE(IsAsciiWordChar('1')); + EXPECT_TRUE(IsAsciiWordChar('7')); + EXPECT_TRUE(IsAsciiWordChar('9')); +} + +TEST(IsAsciiWordCharTest, IsTrueForUnderscore) { + EXPECT_TRUE(IsAsciiWordChar('_')); +} + +TEST(IsValidEscapeTest, IsFalseForNonPrintable) { + EXPECT_FALSE(IsValidEscape('\0')); + EXPECT_FALSE(IsValidEscape('\007')); +} + +TEST(IsValidEscapeTest, IsFalseForDigit) { + EXPECT_FALSE(IsValidEscape('0')); + EXPECT_FALSE(IsValidEscape('9')); +} + +TEST(IsValidEscapeTest, IsFalseForWhiteSpace) { + EXPECT_FALSE(IsValidEscape(' ')); + EXPECT_FALSE(IsValidEscape('\n')); +} + +TEST(IsValidEscapeTest, IsFalseForSomeLetter) { + EXPECT_FALSE(IsValidEscape('a')); + EXPECT_FALSE(IsValidEscape('Z')); +} + +TEST(IsValidEscapeTest, IsTrueForPunct) { + EXPECT_TRUE(IsValidEscape('.')); + EXPECT_TRUE(IsValidEscape('-')); + EXPECT_TRUE(IsValidEscape('^')); + EXPECT_TRUE(IsValidEscape('$')); + EXPECT_TRUE(IsValidEscape('(')); + EXPECT_TRUE(IsValidEscape(']')); + EXPECT_TRUE(IsValidEscape('{')); + EXPECT_TRUE(IsValidEscape('|')); +} + +TEST(IsValidEscapeTest, IsTrueForSomeLetter) { + EXPECT_TRUE(IsValidEscape('d')); + EXPECT_TRUE(IsValidEscape('D')); + EXPECT_TRUE(IsValidEscape('s')); + EXPECT_TRUE(IsValidEscape('S')); + EXPECT_TRUE(IsValidEscape('w')); + EXPECT_TRUE(IsValidEscape('W')); +} + +TEST(AtomMatchesCharTest, EscapedPunct) { + EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, '\\', ' ')); + EXPECT_FALSE(AtomMatchesChar(true, '_', '.')); + EXPECT_FALSE(AtomMatchesChar(true, '.', 'a')); + + EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\')); + EXPECT_TRUE(AtomMatchesChar(true, '_', '_')); + EXPECT_TRUE(AtomMatchesChar(true, '+', '+')); + EXPECT_TRUE(AtomMatchesChar(true, '.', '.')); +} + +TEST(AtomMatchesCharTest, Escaped_d) { + EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a')); + EXPECT_FALSE(AtomMatchesChar(true, 'd', '.')); + + EXPECT_TRUE(AtomMatchesChar(true, 'd', '0')); + EXPECT_TRUE(AtomMatchesChar(true, 'd', '9')); +} + +TEST(AtomMatchesCharTest, Escaped_D) { + EXPECT_FALSE(AtomMatchesChar(true, 'D', '0')); + EXPECT_FALSE(AtomMatchesChar(true, 'D', '9')); + + EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0')); + EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a')); + EXPECT_TRUE(AtomMatchesChar(true, 'D', '-')); +} + +TEST(AtomMatchesCharTest, Escaped_s) { + EXPECT_FALSE(AtomMatchesChar(true, 's', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 's', 'a')); + EXPECT_FALSE(AtomMatchesChar(true, 's', '.')); + EXPECT_FALSE(AtomMatchesChar(true, 's', '9')); + + EXPECT_TRUE(AtomMatchesChar(true, 's', ' ')); + EXPECT_TRUE(AtomMatchesChar(true, 's', '\n')); + EXPECT_TRUE(AtomMatchesChar(true, 's', '\t')); +} + +TEST(AtomMatchesCharTest, Escaped_S) { + EXPECT_FALSE(AtomMatchesChar(true, 'S', ' ')); + EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r')); + + EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0')); + EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a')); + EXPECT_TRUE(AtomMatchesChar(true, 'S', '9')); +} + +TEST(AtomMatchesCharTest, Escaped_w) { + EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 'w', '+')); + EXPECT_FALSE(AtomMatchesChar(true, 'w', ' ')); + EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n')); + + EXPECT_TRUE(AtomMatchesChar(true, 'w', '0')); + EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b')); + EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C')); + EXPECT_TRUE(AtomMatchesChar(true, 'w', '_')); +} + +TEST(AtomMatchesCharTest, Escaped_W) { + EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A')); + EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b')); + EXPECT_FALSE(AtomMatchesChar(true, 'W', '9')); + EXPECT_FALSE(AtomMatchesChar(true, 'W', '_')); + + EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0')); + EXPECT_TRUE(AtomMatchesChar(true, 'W', '*')); + EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n')); +} + +TEST(AtomMatchesCharTest, EscapedWhiteSpace) { + EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n')); + EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r')); + EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a')); + EXPECT_FALSE(AtomMatchesChar(true, 't', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 't', 't')); + EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0')); + EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f')); + + EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f')); + EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n')); + EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r')); + EXPECT_TRUE(AtomMatchesChar(true, 't', '\t')); + EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v')); +} + +TEST(AtomMatchesCharTest, UnescapedDot) { + EXPECT_FALSE(AtomMatchesChar(false, '.', '\n')); + + EXPECT_TRUE(AtomMatchesChar(false, '.', '\0')); + EXPECT_TRUE(AtomMatchesChar(false, '.', '.')); + EXPECT_TRUE(AtomMatchesChar(false, '.', 'a')); + EXPECT_TRUE(AtomMatchesChar(false, '.', ' ')); +} + +TEST(AtomMatchesCharTest, UnescapedChar) { + EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0')); + EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b')); + EXPECT_FALSE(AtomMatchesChar(false, '$', 'a')); + + EXPECT_TRUE(AtomMatchesChar(false, '$', '$')); + EXPECT_TRUE(AtomMatchesChar(false, '5', '5')); + EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z')); +} + +TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) { + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)), + "NULL is not a valid simple regular expression"); + EXPECT_NONFATAL_FAILURE( + ASSERT_FALSE(ValidateRegex("a\\")), + "Syntax error at index 1 in simple regular expression \"a\\\": "); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")), + "'\\' cannot appear at the end"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")), + "'\\' cannot appear at the end"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")), + "invalid escape sequence \"\\h\""); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")), + "'^' can only appear at the beginning"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")), + "'^' can only appear at the beginning"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")), + "'$' can only appear at the end"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")), + "'$' can only appear at the end"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")), + "'(' is unsupported"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")), + "')' is unsupported"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")), + "'[' is unsupported"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")), + "'{' is unsupported"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")), + "'?' can only follow a repeatable token"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")), + "'*' can only follow a repeatable token"); + EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")), + "'+' can only follow a repeatable token"); +} + +TEST(ValidateRegexTest, ReturnsTrueForValid) { + EXPECT_TRUE(ValidateRegex("")); + EXPECT_TRUE(ValidateRegex("a")); + EXPECT_TRUE(ValidateRegex(".*")); + EXPECT_TRUE(ValidateRegex("^a_+")); + EXPECT_TRUE(ValidateRegex("^a\\t\\&?")); + EXPECT_TRUE(ValidateRegex("09*$")); + EXPECT_TRUE(ValidateRegex("^Z$")); + EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}")); +} + +TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) { + EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba")); + // Repeating more than once. + EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab")); + + // Repeating zero times. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba")); + // Repeating once. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab")); + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##")); +} + +TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) { + EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab")); + + // Repeating zero times. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc")); + // Repeating once. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc")); + // Repeating more than once. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g")); +} + +TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) { + EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab")); + // Repeating zero times. + EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc")); + + // Repeating once. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc")); + // Repeating more than once. + EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g")); +} + +TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) { + EXPECT_TRUE(MatchRegexAtHead("", "")); + EXPECT_TRUE(MatchRegexAtHead("", "ab")); +} + +TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) { + EXPECT_FALSE(MatchRegexAtHead("$", "a")); + + EXPECT_TRUE(MatchRegexAtHead("$", "")); + EXPECT_TRUE(MatchRegexAtHead("a$", "a")); +} + +TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) { + EXPECT_FALSE(MatchRegexAtHead("\\w", "+")); + EXPECT_FALSE(MatchRegexAtHead("\\W", "ab")); + + EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab")); + EXPECT_TRUE(MatchRegexAtHead("\\d", "1a")); +} + +TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) { + EXPECT_FALSE(MatchRegexAtHead(".+a", "abc")); + EXPECT_FALSE(MatchRegexAtHead("a?b", "aab")); + + EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab")); + EXPECT_TRUE(MatchRegexAtHead("a?b", "b")); + EXPECT_TRUE(MatchRegexAtHead("a?b", "ab")); +} + +TEST(MatchRegexAtHeadTest, + WorksWhenRegexStartsWithRepetionOfEscapeSequence) { + EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc")); + EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b")); + + EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab")); + EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b")); + EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b")); + EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b")); +} + +TEST(MatchRegexAtHeadTest, MatchesSequentially) { + EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc")); + + EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc")); +} + +TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) { + EXPECT_FALSE(MatchRegexAnywhere("", NULL)); +} + +TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) { + EXPECT_FALSE(MatchRegexAnywhere("^a", "ba")); + EXPECT_FALSE(MatchRegexAnywhere("^$", "a")); + + EXPECT_TRUE(MatchRegexAnywhere("^a", "ab")); + EXPECT_TRUE(MatchRegexAnywhere("^", "ab")); + EXPECT_TRUE(MatchRegexAnywhere("^$", "")); +} + +TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) { + EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123")); + EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888")); +} + +TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) { + EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5")); + EXPECT_TRUE(MatchRegexAnywhere(".*=", "=")); + EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc")); +} + +TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) { + EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5")); + EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...=")); +} + +// Tests RE's implicit constructors. +TEST(RETest, ImplicitConstructorWorks) { + const RE empty(""); + EXPECT_STREQ("", empty.pattern()); + + const RE simple("hello"); + EXPECT_STREQ("hello", simple.pattern()); +} + +// Tests that RE's constructors reject invalid regular expressions. +TEST(RETest, RejectsInvalidRegex) { + EXPECT_NONFATAL_FAILURE({ + const RE normal(NULL); + }, "NULL is not a valid simple regular expression"); + + EXPECT_NONFATAL_FAILURE({ + const RE normal(".*(\\w+"); + }, "'(' is unsupported"); + + EXPECT_NONFATAL_FAILURE({ + const RE invalid("^?"); + }, "'?' can only follow a repeatable token"); +} + +// Tests RE::FullMatch(). +TEST(RETest, FullMatchWorks) { + const RE empty(""); + EXPECT_TRUE(RE::FullMatch("", empty)); + EXPECT_FALSE(RE::FullMatch("a", empty)); + + const RE re1("a"); + EXPECT_TRUE(RE::FullMatch("a", re1)); + + const RE re("a.*z"); + EXPECT_TRUE(RE::FullMatch("az", re)); + EXPECT_TRUE(RE::FullMatch("axyz", re)); + EXPECT_FALSE(RE::FullMatch("baz", re)); + EXPECT_FALSE(RE::FullMatch("azy", re)); +} + +// Tests RE::PartialMatch(). +TEST(RETest, PartialMatchWorks) { + const RE empty(""); + EXPECT_TRUE(RE::PartialMatch("", empty)); + EXPECT_TRUE(RE::PartialMatch("a", empty)); + + const RE re("a.*z"); + EXPECT_TRUE(RE::PartialMatch("az", re)); + EXPECT_TRUE(RE::PartialMatch("axyz", re)); + EXPECT_TRUE(RE::PartialMatch("baz", re)); + EXPECT_TRUE(RE::PartialMatch("azy", re)); + EXPECT_FALSE(RE::PartialMatch("zza", re)); +} + +#endif // GTEST_USES_POSIX_RE + +#if !GTEST_OS_WINDOWS_MOBILE + +TEST(CaptureTest, CapturesStdout) { + CaptureStdout(); + fprintf(stdout, "abc"); + EXPECT_STREQ("abc", GetCapturedStdout().c_str()); + + CaptureStdout(); + fprintf(stdout, "def%cghi", '\0'); + EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout())); +} + +TEST(CaptureTest, CapturesStderr) { + CaptureStderr(); + fprintf(stderr, "jkl"); + EXPECT_STREQ("jkl", GetCapturedStderr().c_str()); + + CaptureStderr(); + fprintf(stderr, "jkl%cmno", '\0'); + EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr())); +} + +// Tests that stdout and stderr capture don't interfere with each other. +TEST(CaptureTest, CapturesStdoutAndStderr) { + CaptureStdout(); + CaptureStderr(); + fprintf(stdout, "pqr"); + fprintf(stderr, "stu"); + EXPECT_STREQ("pqr", GetCapturedStdout().c_str()); + EXPECT_STREQ("stu", GetCapturedStderr().c_str()); +} + +TEST(CaptureDeathTest, CannotReenterStdoutCapture) { + CaptureStdout(); + EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(), + "Only one stdout capturer can exist at a time"); + GetCapturedStdout(); + + // We cannot test stderr capturing using death tests as they use it + // themselves. +} + +#endif // !GTEST_OS_WINDOWS_MOBILE + +TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) { + ThreadLocal t1; + EXPECT_EQ(0, t1.get()); + + ThreadLocal t2; + EXPECT_TRUE(t2.get() == NULL); +} + +TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) { + ThreadLocal t1(123); + EXPECT_EQ(123, t1.get()); + + int i = 0; + ThreadLocal t2(&i); + EXPECT_EQ(&i, t2.get()); +} + +class NoDefaultContructor { + public: + explicit NoDefaultContructor(const char*) {} + NoDefaultContructor(const NoDefaultContructor&) {} +}; + +TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) { + ThreadLocal bar(NoDefaultContructor("foo")); + bar.pointer(); +} + +TEST(ThreadLocalTest, GetAndPointerReturnSameValue) { + ThreadLocal thread_local_string; + + EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get())); + + // Verifies the condition still holds after calling set. + thread_local_string.set("foo"); + EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get())); +} + +TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) { + ThreadLocal thread_local_string; + const ThreadLocal& const_thread_local_string = + thread_local_string; + + EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer()); + + thread_local_string.set("foo"); + EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer()); +} + +#if GTEST_IS_THREADSAFE + +void AddTwo(int* param) { *param += 2; } + +TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) { + int i = 40; + ThreadWithParam thread(&AddTwo, &i, NULL); + thread.Join(); + EXPECT_EQ(42, i); +} + +TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) { + // AssertHeld() is flaky only in the presence of multiple threads accessing + // the lock. In this case, the test is robust. + EXPECT_DEATH_IF_SUPPORTED({ + Mutex m; + { MutexLock lock(&m); } + m.AssertHeld(); + }, + "thread .*hold"); +} + +TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) { + Mutex m; + MutexLock lock(&m); + m.AssertHeld(); +} + +class AtomicCounterWithMutex { + public: + explicit AtomicCounterWithMutex(Mutex* mutex) : + value_(0), mutex_(mutex), random_(42) {} + + void Increment() { + MutexLock lock(mutex_); + int temp = value_; + { + // We need to put up a memory barrier to prevent reads and writes to + // value_ rearranged with the call to SleepMilliseconds when observed + // from other threads. +#if GTEST_HAS_PTHREAD + // On POSIX, locking a mutex puts up a memory barrier. We cannot use + // Mutex and MutexLock here or rely on their memory barrier + // functionality as we are testing them here. + pthread_mutex_t memory_barrier_mutex; + GTEST_CHECK_POSIX_SUCCESS_( + pthread_mutex_init(&memory_barrier_mutex, NULL)); + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex)); + + SleepMilliseconds(random_.Generate(30)); + + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex)); + GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex)); +#elif GTEST_OS_WINDOWS + // On Windows, performing an interlocked access puts up a memory barrier. + volatile LONG dummy = 0; + ::InterlockedIncrement(&dummy); + SleepMilliseconds(random_.Generate(30)); + ::InterlockedIncrement(&dummy); +#else +# error "Memory barrier not implemented on this platform." +#endif // GTEST_HAS_PTHREAD + } + value_ = temp + 1; + } + int value() const { return value_; } + + private: + volatile int value_; + Mutex* const mutex_; // Protects value_. + Random random_; +}; + +void CountingThreadFunc(pair param) { + for (int i = 0; i < param.second; ++i) + param.first->Increment(); +} + +// Tests that the mutex only lets one thread at a time to lock it. +TEST(MutexTest, OnlyOneThreadCanLockAtATime) { + Mutex mutex; + AtomicCounterWithMutex locked_counter(&mutex); + + typedef ThreadWithParam > ThreadType; + const int kCycleCount = 20; + const int kThreadCount = 7; + scoped_ptr counting_threads[kThreadCount]; + Notification threads_can_start; + // Creates and runs kThreadCount threads that increment locked_counter + // kCycleCount times each. + for (int i = 0; i < kThreadCount; ++i) { + counting_threads[i].reset(new ThreadType(&CountingThreadFunc, + make_pair(&locked_counter, + kCycleCount), + &threads_can_start)); + } + threads_can_start.Notify(); + for (int i = 0; i < kThreadCount; ++i) + counting_threads[i]->Join(); + + // If the mutex lets more than one thread to increment the counter at a + // time, they are likely to encounter a race condition and have some + // increments overwritten, resulting in the lower then expected counter + // value. + EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value()); +} + +template +void RunFromThread(void (func)(T), T param) { + ThreadWithParam thread(func, param, NULL); + thread.Join(); +} + +void RetrieveThreadLocalValue( + pair*, std::string*> param) { + *param.second = param.first->get(); +} + +TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) { + ThreadLocal thread_local_string("foo"); + EXPECT_STREQ("foo", thread_local_string.get().c_str()); + + thread_local_string.set("bar"); + EXPECT_STREQ("bar", thread_local_string.get().c_str()); + + std::string result; + RunFromThread(&RetrieveThreadLocalValue, + make_pair(&thread_local_string, &result)); + EXPECT_STREQ("foo", result.c_str()); +} + +// Keeps track of whether of destructors being called on instances of +// DestructorTracker. On Windows, waits for the destructor call reports. +class DestructorCall { + public: + DestructorCall() { + invoked_ = false; +#if GTEST_OS_WINDOWS + wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL)); + GTEST_CHECK_(wait_event_.Get() != NULL); +#endif + } + + bool CheckDestroyed() const { +#if GTEST_OS_WINDOWS + if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0) + return false; +#endif + return invoked_; + } + + void ReportDestroyed() { + invoked_ = true; +#if GTEST_OS_WINDOWS + ::SetEvent(wait_event_.Get()); +#endif + } + + static std::vector& List() { return *list_; } + + static void ResetList() { + for (size_t i = 0; i < list_->size(); ++i) { + delete list_->at(i); + } + list_->clear(); + } + + private: + bool invoked_; +#if GTEST_OS_WINDOWS + AutoHandle wait_event_; +#endif + static std::vector* const list_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall); +}; + +std::vector* const DestructorCall::list_ = + new std::vector; + +// DestructorTracker keeps track of whether its instances have been +// destroyed. +class DestructorTracker { + public: + DestructorTracker() : index_(GetNewIndex()) {} + DestructorTracker(const DestructorTracker& /* rhs */) + : index_(GetNewIndex()) {} + ~DestructorTracker() { + // We never access DestructorCall::List() concurrently, so we don't need + // to protect this access with a mutex. + DestructorCall::List()[index_]->ReportDestroyed(); + } + + private: + static size_t GetNewIndex() { + DestructorCall::List().push_back(new DestructorCall); + return DestructorCall::List().size() - 1; + } + const size_t index_; + + GTEST_DISALLOW_ASSIGN_(DestructorTracker); +}; + +typedef ThreadLocal* ThreadParam; + +void CallThreadLocalGet(ThreadParam thread_local_param) { + thread_local_param->get(); +} + +// Tests that when a ThreadLocal object dies in a thread, it destroys +// the managed object for that thread. +TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) { + DestructorCall::ResetList(); + + { + ThreadLocal thread_local_tracker; + ASSERT_EQ(0U, DestructorCall::List().size()); + + // This creates another DestructorTracker object for the main thread. + thread_local_tracker.get(); + ASSERT_EQ(1U, DestructorCall::List().size()); + ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed()); + } + + // Now thread_local_tracker has died. + ASSERT_EQ(1U, DestructorCall::List().size()); + EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); + + DestructorCall::ResetList(); +} + +// Tests that when a thread exits, the thread-local object for that +// thread is destroyed. +TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) { + DestructorCall::ResetList(); + + { + ThreadLocal thread_local_tracker; + ASSERT_EQ(0U, DestructorCall::List().size()); + + // This creates another DestructorTracker object in the new thread. + ThreadWithParam thread( + &CallThreadLocalGet, &thread_local_tracker, NULL); + thread.Join(); + + // The thread has exited, and we should have a DestroyedTracker + // instance created for it. But it may not have been destroyed yet. + ASSERT_EQ(1U, DestructorCall::List().size()); + } + + // The thread has exited and thread_local_tracker has died. + ASSERT_EQ(1U, DestructorCall::List().size()); + EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); + + DestructorCall::ResetList(); +} + +TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) { + ThreadLocal thread_local_string; + thread_local_string.set("Foo"); + EXPECT_STREQ("Foo", thread_local_string.get().c_str()); + + std::string result; + RunFromThread(&RetrieveThreadLocalValue, + make_pair(&thread_local_string, &result)); + EXPECT_TRUE(result.empty()); +} + +#endif // GTEST_IS_THREADSAFE + +#if GTEST_OS_WINDOWS +TEST(WindowsTypesTest, HANDLEIsVoidStar) { + StaticAssertTypeEq(); +} + +#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) +TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) { + StaticAssertTypeEq(); +} +#else +TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) { + StaticAssertTypeEq(); +} +#endif + +#endif // GTEST_OS_WINDOWS + +} // namespace internal +} // namespace testing diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc new file mode 100644 index 0000000..49b3bd4 --- /dev/null +++ b/googletest/test/googletest-printers-test.cc @@ -0,0 +1,1737 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Test - The Google C++ Testing and Mocking Framework +// +// This file tests the universal value printer. + +#include "gtest/gtest-printers.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gtest/gtest.h" + +#if GTEST_HAS_UNORDERED_MAP_ +# include // NOLINT +#endif // GTEST_HAS_UNORDERED_MAP_ + +#if GTEST_HAS_UNORDERED_SET_ +# include // NOLINT +#endif // GTEST_HAS_UNORDERED_SET_ + +#if GTEST_HAS_STD_FORWARD_LIST_ +# include // NOLINT +#endif // GTEST_HAS_STD_FORWARD_LIST_ + +// Some user-defined types for testing the universal value printer. + +// An anonymous enum type. +enum AnonymousEnum { + kAE1 = -1, + kAE2 = 1 +}; + +// An enum without a user-defined printer. +enum EnumWithoutPrinter { + kEWP1 = -2, + kEWP2 = 42 +}; + +// An enum with a << operator. +enum EnumWithStreaming { + kEWS1 = 10 +}; + +std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) { + return os << (e == kEWS1 ? "kEWS1" : "invalid"); +} + +// An enum with a PrintTo() function. +enum EnumWithPrintTo { + kEWPT1 = 1 +}; + +void PrintTo(EnumWithPrintTo e, std::ostream* os) { + *os << (e == kEWPT1 ? "kEWPT1" : "invalid"); +} + +// A class implicitly convertible to BiggestInt. +class BiggestIntConvertible { + public: + operator ::testing::internal::BiggestInt() const { return 42; } +}; + +// A user-defined unprintable class template in the global namespace. +template +class UnprintableTemplateInGlobal { + public: + UnprintableTemplateInGlobal() : value_() {} + private: + T value_; +}; + +// A user-defined streamable type in the global namespace. +class StreamableInGlobal { + public: + virtual ~StreamableInGlobal() {} +}; + +inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) { + os << "StreamableInGlobal"; +} + +void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) { + os << "StreamableInGlobal*"; +} + +namespace foo { + +// A user-defined unprintable type in a user namespace. +class UnprintableInFoo { + public: + UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); } + double z() const { return z_; } + private: + char xy_[8]; + double z_; +}; + +// A user-defined printable type in a user-chosen namespace. +struct PrintableViaPrintTo { + PrintableViaPrintTo() : value() {} + int value; +}; + +void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) { + *os << "PrintableViaPrintTo: " << x.value; +} + +// A type with a user-defined << for printing its pointer. +struct PointerPrintable { +}; + +::std::ostream& operator<<(::std::ostream& os, + const PointerPrintable* /* x */) { + return os << "PointerPrintable*"; +} + +// A user-defined printable class template in a user-chosen namespace. +template +class PrintableViaPrintToTemplate { + public: + explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {} + + const T& value() const { return value_; } + private: + T value_; +}; + +template +void PrintTo(const PrintableViaPrintToTemplate& x, ::std::ostream* os) { + *os << "PrintableViaPrintToTemplate: " << x.value(); +} + +// A user-defined streamable class template in a user namespace. +template +class StreamableTemplateInFoo { + public: + StreamableTemplateInFoo() : value_() {} + + const T& value() const { return value_; } + private: + T value_; +}; + +template +inline ::std::ostream& operator<<(::std::ostream& os, + const StreamableTemplateInFoo& x) { + return os << "StreamableTemplateInFoo: " << x.value(); +} + +// A user-defined streamable but recursivly-defined container type in +// a user namespace, it mimics therefore std::filesystem::path or +// boost::filesystem::path. +class PathLike { + public: + struct iterator { + typedef PathLike value_type; + }; + + PathLike() {} + + iterator begin() const { return iterator(); } + iterator end() const { return iterator(); } + + friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) { + return os << "Streamable-PathLike"; + } +}; + +} // namespace foo + +namespace testing { +namespace gtest_printers_test { + +using ::std::deque; +using ::std::list; +using ::std::make_pair; +using ::std::map; +using ::std::multimap; +using ::std::multiset; +using ::std::pair; +using ::std::set; +using ::std::vector; +using ::testing::PrintToString; +using ::testing::internal::FormatForComparisonFailureMessage; +using ::testing::internal::ImplicitCast_; +using ::testing::internal::NativeArray; +using ::testing::internal::RE; +using ::testing::internal::RelationToSourceReference; +using ::testing::internal::Strings; +using ::testing::internal::UniversalPrint; +using ::testing::internal::UniversalPrinter; +using ::testing::internal::UniversalTersePrint; +#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ +using ::testing::internal::UniversalTersePrintTupleFieldsToStrings; +#endif + +// Prints a value to a string using the universal value printer. This +// is a helper for testing UniversalPrinter::Print() for various types. +template +std::string Print(const T& value) { + ::std::stringstream ss; + UniversalPrinter::Print(value, &ss); + return ss.str(); +} + +// Prints a value passed by reference to a string, using the universal +// value printer. This is a helper for testing +// UniversalPrinter::Print() for various types. +template +std::string PrintByRef(const T& value) { + ::std::stringstream ss; + UniversalPrinter::Print(value, &ss); + return ss.str(); +} + +// Tests printing various enum types. + +TEST(PrintEnumTest, AnonymousEnum) { + EXPECT_EQ("-1", Print(kAE1)); + EXPECT_EQ("1", Print(kAE2)); +} + +TEST(PrintEnumTest, EnumWithoutPrinter) { + EXPECT_EQ("-2", Print(kEWP1)); + EXPECT_EQ("42", Print(kEWP2)); +} + +TEST(PrintEnumTest, EnumWithStreaming) { + EXPECT_EQ("kEWS1", Print(kEWS1)); + EXPECT_EQ("invalid", Print(static_cast(0))); +} + +TEST(PrintEnumTest, EnumWithPrintTo) { + EXPECT_EQ("kEWPT1", Print(kEWPT1)); + EXPECT_EQ("invalid", Print(static_cast(0))); +} + +// Tests printing a class implicitly convertible to BiggestInt. + +TEST(PrintClassTest, BiggestIntConvertible) { + EXPECT_EQ("42", Print(BiggestIntConvertible())); +} + +// Tests printing various char types. + +// char. +TEST(PrintCharTest, PlainChar) { + EXPECT_EQ("'\\0'", Print('\0')); + EXPECT_EQ("'\\'' (39, 0x27)", Print('\'')); + EXPECT_EQ("'\"' (34, 0x22)", Print('"')); + EXPECT_EQ("'?' (63, 0x3F)", Print('?')); + EXPECT_EQ("'\\\\' (92, 0x5C)", Print('\\')); + EXPECT_EQ("'\\a' (7)", Print('\a')); + EXPECT_EQ("'\\b' (8)", Print('\b')); + EXPECT_EQ("'\\f' (12, 0xC)", Print('\f')); + EXPECT_EQ("'\\n' (10, 0xA)", Print('\n')); + EXPECT_EQ("'\\r' (13, 0xD)", Print('\r')); + EXPECT_EQ("'\\t' (9)", Print('\t')); + EXPECT_EQ("'\\v' (11, 0xB)", Print('\v')); + EXPECT_EQ("'\\x7F' (127)", Print('\x7F')); + EXPECT_EQ("'\\xFF' (255)", Print('\xFF')); + EXPECT_EQ("' ' (32, 0x20)", Print(' ')); + EXPECT_EQ("'a' (97, 0x61)", Print('a')); +} + +// signed char. +TEST(PrintCharTest, SignedChar) { + EXPECT_EQ("'\\0'", Print(static_cast('\0'))); + EXPECT_EQ("'\\xCE' (-50)", + Print(static_cast(-50))); +} + +// unsigned char. +TEST(PrintCharTest, UnsignedChar) { + EXPECT_EQ("'\\0'", Print(static_cast('\0'))); + EXPECT_EQ("'b' (98, 0x62)", + Print(static_cast('b'))); +} + +// Tests printing other simple, built-in types. + +// bool. +TEST(PrintBuiltInTypeTest, Bool) { + EXPECT_EQ("false", Print(false)); + EXPECT_EQ("true", Print(true)); +} + +// wchar_t. +TEST(PrintBuiltInTypeTest, Wchar_t) { + EXPECT_EQ("L'\\0'", Print(L'\0')); + EXPECT_EQ("L'\\'' (39, 0x27)", Print(L'\'')); + EXPECT_EQ("L'\"' (34, 0x22)", Print(L'"')); + EXPECT_EQ("L'?' (63, 0x3F)", Print(L'?')); + EXPECT_EQ("L'\\\\' (92, 0x5C)", Print(L'\\')); + EXPECT_EQ("L'\\a' (7)", Print(L'\a')); + EXPECT_EQ("L'\\b' (8)", Print(L'\b')); + EXPECT_EQ("L'\\f' (12, 0xC)", Print(L'\f')); + EXPECT_EQ("L'\\n' (10, 0xA)", Print(L'\n')); + EXPECT_EQ("L'\\r' (13, 0xD)", Print(L'\r')); + EXPECT_EQ("L'\\t' (9)", Print(L'\t')); + EXPECT_EQ("L'\\v' (11, 0xB)", Print(L'\v')); + EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F')); + EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF')); + EXPECT_EQ("L' ' (32, 0x20)", Print(L' ')); + EXPECT_EQ("L'a' (97, 0x61)", Print(L'a')); + EXPECT_EQ("L'\\x576' (1398)", Print(static_cast(0x576))); + EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast(0xC74D))); +} + +// Test that Int64 provides more storage than wchar_t. +TEST(PrintTypeSizeTest, Wchar_t) { + EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64)); +} + +// Various integer types. +TEST(PrintBuiltInTypeTest, Integer) { + EXPECT_EQ("'\\xFF' (255)", Print(static_cast(255))); // uint8 + EXPECT_EQ("'\\x80' (-128)", Print(static_cast(-128))); // int8 + EXPECT_EQ("65535", Print(USHRT_MAX)); // uint16 + EXPECT_EQ("-32768", Print(SHRT_MIN)); // int16 + EXPECT_EQ("4294967295", Print(UINT_MAX)); // uint32 + EXPECT_EQ("-2147483648", Print(INT_MIN)); // int32 + EXPECT_EQ("18446744073709551615", + Print(static_cast(-1))); // uint64 + EXPECT_EQ("-9223372036854775808", + Print(static_cast(1) << 63)); // int64 +} + +// Size types. +TEST(PrintBuiltInTypeTest, Size_t) { + EXPECT_EQ("1", Print(sizeof('a'))); // size_t. +#if !GTEST_OS_WINDOWS + // Windows has no ssize_t type. + EXPECT_EQ("-2", Print(static_cast(-2))); // ssize_t. +#endif // !GTEST_OS_WINDOWS +} + +// Floating-points. +TEST(PrintBuiltInTypeTest, FloatingPoints) { + EXPECT_EQ("1.5", Print(1.5f)); // float + EXPECT_EQ("-2.5", Print(-2.5)); // double +} + +// Since ::std::stringstream::operator<<(const void *) formats the pointer +// output differently with different compilers, we have to create the expected +// output first and use it as our expectation. +static std::string PrintPointer(const void* p) { + ::std::stringstream expected_result_stream; + expected_result_stream << p; + return expected_result_stream.str(); +} + +// Tests printing C strings. + +// const char*. +TEST(PrintCStringTest, Const) { + const char* p = "World"; + EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p)); +} + +// char*. +TEST(PrintCStringTest, NonConst) { + char p[] = "Hi"; + EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"", + Print(static_cast(p))); +} + +// NULL C string. +TEST(PrintCStringTest, Null) { + const char* p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// Tests that C strings are escaped properly. +TEST(PrintCStringTest, EscapesProperly) { + const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a"; + EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f" + "\\n\\r\\t\\v\\x7F\\xFF a\"", + Print(p)); +} + +// MSVC compiler can be configured to define whar_t as a typedef +// of unsigned short. Defining an overload for const wchar_t* in that case +// would cause pointers to unsigned shorts be printed as wide strings, +// possibly accessing more memory than intended and causing invalid +// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when +// wchar_t is implemented as a native type. +#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) + +// const wchar_t*. +TEST(PrintWideCStringTest, Const) { + const wchar_t* p = L"World"; + EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p)); +} + +// wchar_t*. +TEST(PrintWideCStringTest, NonConst) { + wchar_t p[] = L"Hi"; + EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"", + Print(static_cast(p))); +} + +// NULL wide C string. +TEST(PrintWideCStringTest, Null) { + const wchar_t* p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// Tests that wide C strings are escaped properly. +TEST(PrintWideCStringTest, EscapesProperly) { + const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r', + '\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'}; + EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f" + "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"", + Print(static_cast(s))); +} +#endif // native wchar_t + +// Tests printing pointers to other char types. + +// signed char*. +TEST(PrintCharPointerTest, SignedChar) { + signed char* p = reinterpret_cast(0x1234); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// const signed char*. +TEST(PrintCharPointerTest, ConstSignedChar) { + signed char* p = reinterpret_cast(0x1234); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// unsigned char*. +TEST(PrintCharPointerTest, UnsignedChar) { + unsigned char* p = reinterpret_cast(0x1234); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// const unsigned char*. +TEST(PrintCharPointerTest, ConstUnsignedChar) { + const unsigned char* p = reinterpret_cast(0x1234); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// Tests printing pointers to simple, built-in types. + +// bool*. +TEST(PrintPointerToBuiltInTypeTest, Bool) { + bool* p = reinterpret_cast(0xABCD); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// void*. +TEST(PrintPointerToBuiltInTypeTest, Void) { + void* p = reinterpret_cast(0xABCD); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// const void*. +TEST(PrintPointerToBuiltInTypeTest, ConstVoid) { + const void* p = reinterpret_cast(0xABCD); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// Tests printing pointers to pointers. +TEST(PrintPointerToPointerTest, IntPointerPointer) { + int** p = reinterpret_cast(0xABCD); + EXPECT_EQ(PrintPointer(p), Print(p)); + p = NULL; + EXPECT_EQ("NULL", Print(p)); +} + +// Tests printing (non-member) function pointers. + +void MyFunction(int /* n */) {} + +TEST(PrintPointerTest, NonMemberFunctionPointer) { + // We cannot directly cast &MyFunction to const void* because the + // standard disallows casting between pointers to functions and + // pointers to objects, and some compilers (e.g. GCC 3.4) enforce + // this limitation. + EXPECT_EQ( + PrintPointer(reinterpret_cast( + reinterpret_cast(&MyFunction))), + Print(&MyFunction)); + int (*p)(bool) = NULL; // NOLINT + EXPECT_EQ("NULL", Print(p)); +} + +// An assertion predicate determining whether a one string is a prefix for +// another. +template +AssertionResult HasPrefix(const StringType& str, const StringType& prefix) { + if (str.find(prefix, 0) == 0) + return AssertionSuccess(); + + const bool is_wide_string = sizeof(prefix[0]) > 1; + const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; + return AssertionFailure() + << begin_string_quote << prefix << "\" is not a prefix of " + << begin_string_quote << str << "\"\n"; +} + +// Tests printing member variable pointers. Although they are called +// pointers, they don't point to a location in the address space. +// Their representation is implementation-defined. Thus they will be +// printed as raw bytes. + +struct Foo { + public: + virtual ~Foo() {} + int MyMethod(char x) { return x + 1; } + virtual char MyVirtualMethod(int /* n */) { return 'a'; } + + int value; +}; + +TEST(PrintPointerTest, MemberVariablePointer) { + EXPECT_TRUE(HasPrefix(Print(&Foo::value), + Print(sizeof(&Foo::value)) + "-byte object ")); + int (Foo::*p) = NULL; // NOLINT + EXPECT_TRUE(HasPrefix(Print(p), + Print(sizeof(p)) + "-byte object ")); +} + +// Tests printing member function pointers. Although they are called +// pointers, they don't point to a location in the address space. +// Their representation is implementation-defined. Thus they will be +// printed as raw bytes. +TEST(PrintPointerTest, MemberFunctionPointer) { + EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod), + Print(sizeof(&Foo::MyMethod)) + "-byte object ")); + EXPECT_TRUE( + HasPrefix(Print(&Foo::MyVirtualMethod), + Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object ")); + int (Foo::*p)(char) = NULL; // NOLINT + EXPECT_TRUE(HasPrefix(Print(p), + Print(sizeof(p)) + "-byte object ")); +} + +// Tests printing C arrays. + +// The difference between this and Print() is that it ensures that the +// argument is a reference to an array. +template +std::string PrintArrayHelper(T (&a)[N]) { + return Print(a); +} + +// One-dimensional array. +TEST(PrintArrayTest, OneDimensionalArray) { + int a[5] = { 1, 2, 3, 4, 5 }; + EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a)); +} + +// Two-dimensional array. +TEST(PrintArrayTest, TwoDimensionalArray) { + int a[2][5] = { + { 1, 2, 3, 4, 5 }, + { 6, 7, 8, 9, 0 } + }; + EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a)); +} + +// Array of const elements. +TEST(PrintArrayTest, ConstArray) { + const bool a[1] = { false }; + EXPECT_EQ("{ false }", PrintArrayHelper(a)); +} + +// char array without terminating NUL. +TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) { + // Array a contains '\0' in the middle and doesn't end with '\0'. + char a[] = { 'H', '\0', 'i' }; + EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a)); +} + +// const char array with terminating NUL. +TEST(PrintArrayTest, ConstCharArrayWithTerminatingNul) { + const char a[] = "\0Hi"; + EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a)); +} + +// const wchar_t array without terminating NUL. +TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) { + // Array a contains '\0' in the middle and doesn't end with '\0'. + const wchar_t a[] = { L'H', L'\0', L'i' }; + EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a)); +} + +// wchar_t array with terminating NUL. +TEST(PrintArrayTest, WConstCharArrayWithTerminatingNul) { + const wchar_t a[] = L"\0Hi"; + EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a)); +} + +// Array of objects. +TEST(PrintArrayTest, ObjectArray) { + std::string a[3] = {"Hi", "Hello", "Ni hao"}; + EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a)); +} + +// Array with many elements. +TEST(PrintArrayTest, BigArray) { + int a[100] = { 1, 2, 3 }; + EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }", + PrintArrayHelper(a)); +} + +// Tests printing ::string and ::std::string. + +#if GTEST_HAS_GLOBAL_STRING +// ::string. +TEST(PrintStringTest, StringInGlobalNamespace) { + const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; + const ::string str(s, sizeof(s)); + EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"", + Print(str)); +} +#endif // GTEST_HAS_GLOBAL_STRING + +// ::std::string. +TEST(PrintStringTest, StringInStdNamespace) { + const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; + const ::std::string str(s, sizeof(s)); + EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"", + Print(str)); +} + +TEST(PrintStringTest, StringAmbiguousHex) { + // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of: + // '\x6', '\x6B', or '\x6BA'. + + // a hex escaping sequence following by a decimal digit + EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3"))); + // a hex escaping sequence following by a hex digit (lower-case) + EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas"))); + // a hex escaping sequence following by a hex digit (upper-case) + EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA"))); + // a hex escaping sequence following by a non-xdigit + EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!"))); +} + +// Tests printing ::wstring and ::std::wstring. + +#if GTEST_HAS_GLOBAL_WSTRING +// ::wstring. +TEST(PrintWideStringTest, StringInGlobalNamespace) { + const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; + const ::wstring str(s, sizeof(s)/sizeof(wchar_t)); + EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" + "\\xD3\\x576\\x8D3\\xC74D a\\0\"", + Print(str)); +} +#endif // GTEST_HAS_GLOBAL_WSTRING + +#if GTEST_HAS_STD_WSTRING +// ::std::wstring. +TEST(PrintWideStringTest, StringInStdNamespace) { + const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; + const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t)); + EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" + "\\xD3\\x576\\x8D3\\xC74D a\\0\"", + Print(str)); +} + +TEST(PrintWideStringTest, StringAmbiguousHex) { + // same for wide strings. + EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3"))); + EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", + Print(::std::wstring(L"mm\x6" L"bananas"))); + EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", + Print(::std::wstring(L"NOM\x6" L"BANANA"))); + EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!"))); +} +#endif // GTEST_HAS_STD_WSTRING + +// Tests printing types that support generic streaming (i.e. streaming +// to std::basic_ostream for any valid Char and +// CharTraits types). + +// Tests printing a non-template type that supports generic streaming. + +class AllowsGenericStreaming {}; + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, + const AllowsGenericStreaming& /* a */) { + return os << "AllowsGenericStreaming"; +} + +TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) { + AllowsGenericStreaming a; + EXPECT_EQ("AllowsGenericStreaming", Print(a)); +} + +// Tests printing a template type that supports generic streaming. + +template +class AllowsGenericStreamingTemplate {}; + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, + const AllowsGenericStreamingTemplate& /* a */) { + return os << "AllowsGenericStreamingTemplate"; +} + +TEST(PrintTypeWithGenericStreamingTest, TemplateType) { + AllowsGenericStreamingTemplate a; + EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a)); +} + +// Tests printing a type that supports generic streaming and can be +// implicitly converted to another printable type. + +template +class AllowsGenericStreamingAndImplicitConversionTemplate { + public: + operator bool() const { return false; } +}; + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, + const AllowsGenericStreamingAndImplicitConversionTemplate& /* a */) { + return os << "AllowsGenericStreamingAndImplicitConversionTemplate"; +} + +TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) { + AllowsGenericStreamingAndImplicitConversionTemplate a; + EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a)); +} + +#if GTEST_HAS_ABSL + +// Tests printing ::absl::string_view. + +TEST(PrintStringViewTest, SimpleStringView) { + const ::absl::string_view sp = "Hello"; + EXPECT_EQ("\"Hello\"", Print(sp)); +} + +TEST(PrintStringViewTest, UnprintableCharacters) { + const char str[] = "NUL (\0) and \r\t"; + const ::absl::string_view sp(str, sizeof(str) - 1); + EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp)); +} + +#endif // GTEST_HAS_ABSL + +// Tests printing STL containers. + +TEST(PrintStlContainerTest, EmptyDeque) { + deque empty; + EXPECT_EQ("{}", Print(empty)); +} + +TEST(PrintStlContainerTest, NonEmptyDeque) { + deque non_empty; + non_empty.push_back(1); + non_empty.push_back(3); + EXPECT_EQ("{ 1, 3 }", Print(non_empty)); +} + +#if GTEST_HAS_UNORDERED_MAP_ + +TEST(PrintStlContainerTest, OneElementHashMap) { + ::std::unordered_map map1; + map1[1] = 'a'; + EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1)); +} + +TEST(PrintStlContainerTest, HashMultiMap) { + ::std::unordered_multimap map1; + map1.insert(make_pair(5, true)); + map1.insert(make_pair(5, false)); + + // Elements of hash_multimap can be printed in any order. + const std::string result = Print(map1); + EXPECT_TRUE(result == "{ (5, true), (5, false) }" || + result == "{ (5, false), (5, true) }") + << " where Print(map1) returns \"" << result << "\"."; +} + +#endif // GTEST_HAS_UNORDERED_MAP_ + +#if GTEST_HAS_UNORDERED_SET_ + +TEST(PrintStlContainerTest, HashSet) { + ::std::unordered_set set1; + set1.insert(1); + EXPECT_EQ("{ 1 }", Print(set1)); +} + +TEST(PrintStlContainerTest, HashMultiSet) { + const int kSize = 5; + int a[kSize] = { 1, 1, 2, 5, 1 }; + ::std::unordered_multiset set1(a, a + kSize); + + // Elements of hash_multiset can be printed in any order. + const std::string result = Print(set1); + const std::string expected_pattern = "{ d, d, d, d, d }"; // d means a digit. + + // Verifies the result matches the expected pattern; also extracts + // the numbers in the result. + ASSERT_EQ(expected_pattern.length(), result.length()); + std::vector numbers; + for (size_t i = 0; i != result.length(); i++) { + if (expected_pattern[i] == 'd') { + ASSERT_NE(isdigit(static_cast(result[i])), 0); + numbers.push_back(result[i] - '0'); + } else { + EXPECT_EQ(expected_pattern[i], result[i]) << " where result is " + << result; + } + } + + // Makes sure the result contains the right numbers. + std::sort(numbers.begin(), numbers.end()); + std::sort(a, a + kSize); + EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); +} + +#endif // GTEST_HAS_UNORDERED_SET_ + +TEST(PrintStlContainerTest, List) { + const std::string a[] = {"hello", "world"}; + const list strings(a, a + 2); + EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings)); +} + +TEST(PrintStlContainerTest, Map) { + map map1; + map1[1] = true; + map1[5] = false; + map1[3] = true; + EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1)); +} + +TEST(PrintStlContainerTest, MultiMap) { + multimap map1; + // The make_pair template function would deduce the type as + // pair here, and since the key part in a multimap has to + // be constant, without a templated ctor in the pair class (as in + // libCstd on Solaris), make_pair call would fail to compile as no + // implicit conversion is found. Thus explicit typename is used + // here instead. + map1.insert(pair(true, 0)); + map1.insert(pair(true, 1)); + map1.insert(pair(false, 2)); + EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1)); +} + +TEST(PrintStlContainerTest, Set) { + const unsigned int a[] = { 3, 0, 5 }; + set set1(a, a + 3); + EXPECT_EQ("{ 0, 3, 5 }", Print(set1)); +} + +TEST(PrintStlContainerTest, MultiSet) { + const int a[] = { 1, 1, 2, 5, 1 }; + multiset set1(a, a + 5); + EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1)); +} + +#if GTEST_HAS_STD_FORWARD_LIST_ +// is available on Linux in the google3 mode, but not on +// Windows or Mac OS X. + +TEST(PrintStlContainerTest, SinglyLinkedList) { + int a[] = { 9, 2, 8 }; + const std::forward_list ints(a, a + 3); + EXPECT_EQ("{ 9, 2, 8 }", Print(ints)); +} +#endif // GTEST_HAS_STD_FORWARD_LIST_ + +TEST(PrintStlContainerTest, Pair) { + pair p(true, 5); + EXPECT_EQ("(true, 5)", Print(p)); +} + +TEST(PrintStlContainerTest, Vector) { + vector v; + v.push_back(1); + v.push_back(2); + EXPECT_EQ("{ 1, 2 }", Print(v)); +} + +TEST(PrintStlContainerTest, LongSequence) { + const int a[100] = { 1, 2, 3 }; + const vector v(a, a + 100); + EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v)); +} + +TEST(PrintStlContainerTest, NestedContainer) { + const int a1[] = { 1, 2 }; + const int a2[] = { 3, 4, 5 }; + const list l1(a1, a1 + 2); + const list l2(a2, a2 + 3); + + vector > v; + v.push_back(l1); + v.push_back(l2); + EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v)); +} + +TEST(PrintStlContainerTest, OneDimensionalNativeArray) { + const int a[3] = { 1, 2, 3 }; + NativeArray b(a, 3, RelationToSourceReference()); + EXPECT_EQ("{ 1, 2, 3 }", Print(b)); +} + +TEST(PrintStlContainerTest, TwoDimensionalNativeArray) { + const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; + NativeArray b(a, 2, RelationToSourceReference()); + EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b)); +} + +// Tests that a class named iterator isn't treated as a container. + +struct iterator { + char x; +}; + +TEST(PrintStlContainerTest, Iterator) { + iterator it = {}; + EXPECT_EQ("1-byte object <00>", Print(it)); +} + +// Tests that a class named const_iterator isn't treated as a container. + +struct const_iterator { + char x; +}; + +TEST(PrintStlContainerTest, ConstIterator) { + const_iterator it = {}; + EXPECT_EQ("1-byte object <00>", Print(it)); +} + +#if GTEST_HAS_TR1_TUPLE +// Tests printing ::std::tr1::tuples. + +// Tuples of various arities. +TEST(PrintTr1TupleTest, VariousSizes) { + ::std::tr1::tuple<> t0; + EXPECT_EQ("()", Print(t0)); + + ::std::tr1::tuple t1(5); + EXPECT_EQ("(5)", Print(t1)); + + ::std::tr1::tuple t2('a', true); + EXPECT_EQ("('a' (97, 0x61), true)", Print(t2)); + + ::std::tr1::tuple t3(false, 2, 3); + EXPECT_EQ("(false, 2, 3)", Print(t3)); + + ::std::tr1::tuple t4(false, 2, 3, 4); + EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); + + ::std::tr1::tuple t5(false, 2, 3, 4, true); + EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5)); + + ::std::tr1::tuple t6(false, 2, 3, 4, true, 6); + EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6)); + + ::std::tr1::tuple t7( + false, 2, 3, 4, true, 6, 7); + EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7)); + + ::std::tr1::tuple t8( + false, 2, 3, 4, true, 6, 7, true); + EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8)); + + ::std::tr1::tuple t9( + false, 2, 3, 4, true, 6, 7, true, 9); + EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9)); + + const char* const str = "8"; + // VC++ 2010's implementation of tuple of C++0x is deficient, requiring + // an explicit type cast of NULL to be used. + ::std::tr1::tuple + t10(false, 'a', static_cast(3), 4, 5, 1.5F, -2.5, str, // NOLINT + ImplicitCast_(NULL), "10"); + EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + + " pointing to \"8\", NULL, \"10\")", + Print(t10)); +} + +// Nested tuples. +TEST(PrintTr1TupleTest, NestedTuple) { + ::std::tr1::tuple< ::std::tr1::tuple, char> nested( + ::std::tr1::make_tuple(5, true), 'a'); + EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); +} + +#endif // GTEST_HAS_TR1_TUPLE + +#if GTEST_HAS_STD_TUPLE_ +// Tests printing ::std::tuples. + +// Tuples of various arities. +TEST(PrintStdTupleTest, VariousSizes) { + ::std::tuple<> t0; + EXPECT_EQ("()", Print(t0)); + + ::std::tuple t1(5); + EXPECT_EQ("(5)", Print(t1)); + + ::std::tuple t2('a', true); + EXPECT_EQ("('a' (97, 0x61), true)", Print(t2)); + + ::std::tuple t3(false, 2, 3); + EXPECT_EQ("(false, 2, 3)", Print(t3)); + + ::std::tuple t4(false, 2, 3, 4); + EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); + + ::std::tuple t5(false, 2, 3, 4, true); + EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5)); + + ::std::tuple t6(false, 2, 3, 4, true, 6); + EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6)); + + ::std::tuple t7( + false, 2, 3, 4, true, 6, 7); + EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7)); + + ::std::tuple t8( + false, 2, 3, 4, true, 6, 7, true); + EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8)); + + ::std::tuple t9( + false, 2, 3, 4, true, 6, 7, true, 9); + EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9)); + + const char* const str = "8"; + // VC++ 2010's implementation of tuple of C++0x is deficient, requiring + // an explicit type cast of NULL to be used. + ::std::tuple + t10(false, 'a', static_cast(3), 4, 5, 1.5F, -2.5, str, // NOLINT + ImplicitCast_(NULL), "10"); + EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + + " pointing to \"8\", NULL, \"10\")", + Print(t10)); +} + +// Nested tuples. +TEST(PrintStdTupleTest, NestedTuple) { + ::std::tuple< ::std::tuple, char> nested( + ::std::make_tuple(5, true), 'a'); + EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); +} + +#endif // GTEST_LANG_CXX11 + +#if GTEST_LANG_CXX11 +TEST(PrintNullptrT, Basic) { + EXPECT_EQ("(nullptr)", Print(nullptr)); +} +#endif // GTEST_LANG_CXX11 + +// Tests printing user-defined unprintable types. + +// Unprintable types in the global namespace. +TEST(PrintUnprintableTypeTest, InGlobalNamespace) { + EXPECT_EQ("1-byte object <00>", + Print(UnprintableTemplateInGlobal())); +} + +// Unprintable types in a user namespace. +TEST(PrintUnprintableTypeTest, InUserNamespace) { + EXPECT_EQ("16-byte object ", + Print(::foo::UnprintableInFoo())); +} + +// Unprintable types are that too big to be printed completely. + +struct Big { + Big() { memset(array, 0, sizeof(array)); } + char array[257]; +}; + +TEST(PrintUnpritableTypeTest, BigObject) { + EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " + "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>", + Print(Big())); +} + +// Tests printing user-defined streamable types. + +// Streamable types in the global namespace. +TEST(PrintStreamableTypeTest, InGlobalNamespace) { + StreamableInGlobal x; + EXPECT_EQ("StreamableInGlobal", Print(x)); + EXPECT_EQ("StreamableInGlobal*", Print(&x)); +} + +// Printable template types in a user namespace. +TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) { + EXPECT_EQ("StreamableTemplateInFoo: 0", + Print(::foo::StreamableTemplateInFoo())); +} + +// Tests printing a user-defined recursive container type that has a << +// operator. +TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) { + ::foo::PathLike x; + EXPECT_EQ("Streamable-PathLike", Print(x)); + const ::foo::PathLike cx; + EXPECT_EQ("Streamable-PathLike", Print(cx)); +} + +// Tests printing user-defined types that have a PrintTo() function. +TEST(PrintPrintableTypeTest, InUserNamespace) { + EXPECT_EQ("PrintableViaPrintTo: 0", + Print(::foo::PrintableViaPrintTo())); +} + +// Tests printing a pointer to a user-defined type that has a << +// operator for its pointer. +TEST(PrintPrintableTypeTest, PointerInUserNamespace) { + ::foo::PointerPrintable x; + EXPECT_EQ("PointerPrintable*", Print(&x)); +} + +// Tests printing user-defined class template that have a PrintTo() function. +TEST(PrintPrintableTypeTest, TemplateInUserNamespace) { + EXPECT_EQ("PrintableViaPrintToTemplate: 5", + Print(::foo::PrintableViaPrintToTemplate(5))); +} + +// Tests that the universal printer prints both the address and the +// value of a reference. +TEST(PrintReferenceTest, PrintsAddressAndValue) { + int n = 5; + EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n)); + + int a[2][3] = { + { 0, 1, 2 }, + { 3, 4, 5 } + }; + EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }", + PrintByRef(a)); + + const ::foo::UnprintableInFoo x; + EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object " + "", + PrintByRef(x)); +} + +// Tests that the universal printer prints a function pointer passed by +// reference. +TEST(PrintReferenceTest, HandlesFunctionPointer) { + void (*fp)(int n) = &MyFunction; + const std::string fp_pointer_string = + PrintPointer(reinterpret_cast(&fp)); + // We cannot directly cast &MyFunction to const void* because the + // standard disallows casting between pointers to functions and + // pointers to objects, and some compilers (e.g. GCC 3.4) enforce + // this limitation. + const std::string fp_string = PrintPointer(reinterpret_cast( + reinterpret_cast(fp))); + EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, + PrintByRef(fp)); +} + +// Tests that the universal printer prints a member function pointer +// passed by reference. +TEST(PrintReferenceTest, HandlesMemberFunctionPointer) { + int (Foo::*p)(char ch) = &Foo::MyMethod; + EXPECT_TRUE(HasPrefix( + PrintByRef(p), + "@" + PrintPointer(reinterpret_cast(&p)) + " " + + Print(sizeof(p)) + "-byte object ")); + + char (Foo::*p2)(int n) = &Foo::MyVirtualMethod; + EXPECT_TRUE(HasPrefix( + PrintByRef(p2), + "@" + PrintPointer(reinterpret_cast(&p2)) + " " + + Print(sizeof(p2)) + "-byte object ")); +} + +// Tests that the universal printer prints a member variable pointer +// passed by reference. +TEST(PrintReferenceTest, HandlesMemberVariablePointer) { + int (Foo::*p) = &Foo::value; // NOLINT + EXPECT_TRUE(HasPrefix( + PrintByRef(p), + "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object ")); +} + +// Tests that FormatForComparisonFailureMessage(), which is used to print +// an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion +// fails, formats the operand in the desired way. + +// scalar +TEST(FormatForComparisonFailureMessageTest, WorksForScalar) { + EXPECT_STREQ("123", + FormatForComparisonFailureMessage(123, 124).c_str()); +} + +// non-char pointer +TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) { + int n = 0; + EXPECT_EQ(PrintPointer(&n), + FormatForComparisonFailureMessage(&n, &n).c_str()); +} + +// non-char array +TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) { + // In expression 'array == x', 'array' is compared by pointer. + // Therefore we want to print an array operand as a pointer. + int n[] = { 1, 2, 3 }; + EXPECT_EQ(PrintPointer(n), + FormatForComparisonFailureMessage(n, n).c_str()); +} + +// Tests formatting a char pointer when it's compared with another pointer. +// In this case we want to print it as a raw pointer, as the comparison is by +// pointer. + +// char pointer vs pointer +TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) { + // In expression 'p == x', where 'p' and 'x' are (const or not) char + // pointers, the operands are compared by pointer. Therefore we + // want to print 'p' as a pointer instead of a C string (we don't + // even know if it's supposed to point to a valid C string). + + // const char* + const char* s = "hello"; + EXPECT_EQ(PrintPointer(s), + FormatForComparisonFailureMessage(s, s).c_str()); + + // char* + char ch = 'a'; + EXPECT_EQ(PrintPointer(&ch), + FormatForComparisonFailureMessage(&ch, &ch).c_str()); +} + +// wchar_t pointer vs pointer +TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) { + // In expression 'p == x', where 'p' and 'x' are (const or not) char + // pointers, the operands are compared by pointer. Therefore we + // want to print 'p' as a pointer instead of a wide C string (we don't + // even know if it's supposed to point to a valid wide C string). + + // const wchar_t* + const wchar_t* s = L"hello"; + EXPECT_EQ(PrintPointer(s), + FormatForComparisonFailureMessage(s, s).c_str()); + + // wchar_t* + wchar_t ch = L'a'; + EXPECT_EQ(PrintPointer(&ch), + FormatForComparisonFailureMessage(&ch, &ch).c_str()); +} + +// Tests formatting a char pointer when it's compared to a string object. +// In this case we want to print the char pointer as a C string. + +#if GTEST_HAS_GLOBAL_STRING +// char pointer vs ::string +TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsString) { + const char* s = "hello \"world"; + EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped. + FormatForComparisonFailureMessage(s, ::string()).c_str()); + + // char* + char str[] = "hi\1"; + char* p = str; + EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped. + FormatForComparisonFailureMessage(p, ::string()).c_str()); +} +#endif + +// char pointer vs std::string +TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) { + const char* s = "hello \"world"; + EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped. + FormatForComparisonFailureMessage(s, ::std::string()).c_str()); + + // char* + char str[] = "hi\1"; + char* p = str; + EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped. + FormatForComparisonFailureMessage(p, ::std::string()).c_str()); +} + +#if GTEST_HAS_GLOBAL_WSTRING +// wchar_t pointer vs ::wstring +TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsWString) { + const wchar_t* s = L"hi \"world"; + EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped. + FormatForComparisonFailureMessage(s, ::wstring()).c_str()); + + // wchar_t* + wchar_t str[] = L"hi\1"; + wchar_t* p = str; + EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped. + FormatForComparisonFailureMessage(p, ::wstring()).c_str()); +} +#endif + +#if GTEST_HAS_STD_WSTRING +// wchar_t pointer vs std::wstring +TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) { + const wchar_t* s = L"hi \"world"; + EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped. + FormatForComparisonFailureMessage(s, ::std::wstring()).c_str()); + + // wchar_t* + wchar_t str[] = L"hi\1"; + wchar_t* p = str; + EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped. + FormatForComparisonFailureMessage(p, ::std::wstring()).c_str()); +} +#endif + +// Tests formatting a char array when it's compared with a pointer or array. +// In this case we want to print the array as a row pointer, as the comparison +// is by pointer. + +// char array vs pointer +TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) { + char str[] = "hi \"world\""; + char* p = NULL; + EXPECT_EQ(PrintPointer(str), + FormatForComparisonFailureMessage(str, p).c_str()); +} + +// char array vs char array +TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) { + const char str[] = "hi \"world\""; + EXPECT_EQ(PrintPointer(str), + FormatForComparisonFailureMessage(str, str).c_str()); +} + +// wchar_t array vs pointer +TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) { + wchar_t str[] = L"hi \"world\""; + wchar_t* p = NULL; + EXPECT_EQ(PrintPointer(str), + FormatForComparisonFailureMessage(str, p).c_str()); +} + +// wchar_t array vs wchar_t array +TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) { + const wchar_t str[] = L"hi \"world\""; + EXPECT_EQ(PrintPointer(str), + FormatForComparisonFailureMessage(str, str).c_str()); +} + +// Tests formatting a char array when it's compared with a string object. +// In this case we want to print the array as a C string. + +#if GTEST_HAS_GLOBAL_STRING +// char array vs string +TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsString) { + const char str[] = "hi \"w\0rld\""; + EXPECT_STREQ("\"hi \\\"w\"", // The content should be escaped. + // Embedded NUL terminates the string. + FormatForComparisonFailureMessage(str, ::string()).c_str()); +} +#endif + +// char array vs std::string +TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) { + const char str[] = "hi \"world\""; + EXPECT_STREQ("\"hi \\\"world\\\"\"", // The content should be escaped. + FormatForComparisonFailureMessage(str, ::std::string()).c_str()); +} + +#if GTEST_HAS_GLOBAL_WSTRING +// wchar_t array vs wstring +TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWString) { + const wchar_t str[] = L"hi \"world\""; + EXPECT_STREQ("L\"hi \\\"world\\\"\"", // The content should be escaped. + FormatForComparisonFailureMessage(str, ::wstring()).c_str()); +} +#endif + +#if GTEST_HAS_STD_WSTRING +// wchar_t array vs std::wstring +TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) { + const wchar_t str[] = L"hi \"w\0rld\""; + EXPECT_STREQ( + "L\"hi \\\"w\"", // The content should be escaped. + // Embedded NUL terminates the string. + FormatForComparisonFailureMessage(str, ::std::wstring()).c_str()); +} +#endif + +// Useful for testing PrintToString(). We cannot use EXPECT_EQ() +// there as its implementation uses PrintToString(). The caller must +// ensure that 'value' has no side effect. +#define EXPECT_PRINT_TO_STRING_(value, expected_string) \ + EXPECT_TRUE(PrintToString(value) == (expected_string)) \ + << " where " #value " prints as " << (PrintToString(value)) + +TEST(PrintToStringTest, WorksForScalar) { + EXPECT_PRINT_TO_STRING_(123, "123"); +} + +TEST(PrintToStringTest, WorksForPointerToConstChar) { + const char* p = "hello"; + EXPECT_PRINT_TO_STRING_(p, "\"hello\""); +} + +TEST(PrintToStringTest, WorksForPointerToNonConstChar) { + char s[] = "hello"; + char* p = s; + EXPECT_PRINT_TO_STRING_(p, "\"hello\""); +} + +TEST(PrintToStringTest, EscapesForPointerToConstChar) { + const char* p = "hello\n"; + EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\""); +} + +TEST(PrintToStringTest, EscapesForPointerToNonConstChar) { + char s[] = "hello\1"; + char* p = s; + EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\""); +} + +TEST(PrintToStringTest, WorksForArray) { + int n[3] = { 1, 2, 3 }; + EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }"); +} + +TEST(PrintToStringTest, WorksForCharArray) { + char s[] = "hello"; + EXPECT_PRINT_TO_STRING_(s, "\"hello\""); +} + +TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) { + const char str_with_nul[] = "hello\0 world"; + EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\""); + + char mutable_str_with_nul[] = "hello\0 world"; + EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\""); +} + + TEST(PrintToStringTest, ContainsNonLatin) { + // Sanity test with valid UTF-8. Prints both in hex and as text. + std::string non_ascii_str = ::std::string("오전 4:30"); + EXPECT_PRINT_TO_STRING_(non_ascii_str, + "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n" + " As Text: \"오전 4:30\""); + non_ascii_str = ::std::string("From ä — ẑ"); + EXPECT_PRINT_TO_STRING_(non_ascii_str, + "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\"" + "\n As Text: \"From ä — ẑ\""); +} + +TEST(IsValidUTF8Test, IllFormedUTF8) { + // The following test strings are ill-formed UTF-8 and are printed + // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is + // expected to fail, thus output does not contain "As Text:". + + static const char *const kTestdata[][2] = { + // 2-byte lead byte followed by a single-byte character. + {"\xC3\x74", "\"\\xC3t\""}, + // Valid 2-byte character followed by an orphan trail byte. + {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""}, + // Lead byte without trail byte. + {"abc\xC3", "\"abc\\xC3\""}, + // 3-byte lead byte, single-byte character, orphan trail byte. + {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""}, + // Truncated 3-byte character. + {"\xE2\x80", "\"\\xE2\\x80\""}, + // Truncated 3-byte character followed by valid 2-byte char. + {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""}, + // Truncated 3-byte character followed by a single-byte character. + {"\xE2\x80\x7A", "\"\\xE2\\x80z\""}, + // 3-byte lead byte followed by valid 3-byte character. + {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""}, + // 4-byte lead byte followed by valid 3-byte character. + {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""}, + // Truncated 4-byte character. + {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""}, + // Invalid UTF-8 byte sequences embedded in other chars. + {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""}, + {"abc\xC3\x84\xE2\x80\xC3\x84xyz", + "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""}, + // Non-shortest UTF-8 byte sequences are also ill-formed. + // The classics: xC0, xC1 lead byte. + {"\xC0\x80", "\"\\xC0\\x80\""}, + {"\xC1\x81", "\"\\xC1\\x81\""}, + // Non-shortest sequences. + {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""}, + {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""}, + // Last valid code point before surrogate range, should be printed as text, + // too. + {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"퟿\""}, + // Start of surrogate lead. Surrogates are not printed as text. + {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""}, + // Last non-private surrogate lead. + {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""}, + // First private-use surrogate lead. + {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""}, + // Last private-use surrogate lead. + {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""}, + // Mid-point of surrogate trail. + {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""}, + // First valid code point after surrogate range, should be printed as text, + // too. + {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""} + }; + + for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) { + EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]); + } +} + +#undef EXPECT_PRINT_TO_STRING_ + +TEST(UniversalTersePrintTest, WorksForNonReference) { + ::std::stringstream ss; + UniversalTersePrint(123, &ss); + EXPECT_EQ("123", ss.str()); +} + +TEST(UniversalTersePrintTest, WorksForReference) { + const int& n = 123; + ::std::stringstream ss; + UniversalTersePrint(n, &ss); + EXPECT_EQ("123", ss.str()); +} + +TEST(UniversalTersePrintTest, WorksForCString) { + const char* s1 = "abc"; + ::std::stringstream ss1; + UniversalTersePrint(s1, &ss1); + EXPECT_EQ("\"abc\"", ss1.str()); + + char* s2 = const_cast(s1); + ::std::stringstream ss2; + UniversalTersePrint(s2, &ss2); + EXPECT_EQ("\"abc\"", ss2.str()); + + const char* s3 = NULL; + ::std::stringstream ss3; + UniversalTersePrint(s3, &ss3); + EXPECT_EQ("NULL", ss3.str()); +} + +TEST(UniversalPrintTest, WorksForNonReference) { + ::std::stringstream ss; + UniversalPrint(123, &ss); + EXPECT_EQ("123", ss.str()); +} + +TEST(UniversalPrintTest, WorksForReference) { + const int& n = 123; + ::std::stringstream ss; + UniversalPrint(n, &ss); + EXPECT_EQ("123", ss.str()); +} + +TEST(UniversalPrintTest, WorksForCString) { + const char* s1 = "abc"; + ::std::stringstream ss1; + UniversalPrint(s1, &ss1); + EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str())); + + char* s2 = const_cast(s1); + ::std::stringstream ss2; + UniversalPrint(s2, &ss2); + EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str())); + + const char* s3 = NULL; + ::std::stringstream ss3; + UniversalPrint(s3, &ss3); + EXPECT_EQ("NULL", ss3.str()); +} + +TEST(UniversalPrintTest, WorksForCharArray) { + const char str[] = "\"Line\0 1\"\nLine 2"; + ::std::stringstream ss1; + UniversalPrint(str, &ss1); + EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str()); + + const char mutable_str[] = "\"Line\0 1\"\nLine 2"; + ::std::stringstream ss2; + UniversalPrint(mutable_str, &ss2); + EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str()); +} + +#if GTEST_HAS_TR1_TUPLE + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsEmptyTuple) { + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::tr1::make_tuple()); + EXPECT_EQ(0u, result.size()); +} + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsOneTuple) { + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::tr1::make_tuple(1)); + ASSERT_EQ(1u, result.size()); + EXPECT_EQ("1", result[0]); +} + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTwoTuple) { + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::tr1::make_tuple(1, 'a')); + ASSERT_EQ(2u, result.size()); + EXPECT_EQ("1", result[0]); + EXPECT_EQ("'a' (97, 0x61)", result[1]); +} + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTersely) { + const int n = 1; + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::tr1::tuple(n, "a")); + ASSERT_EQ(2u, result.size()); + EXPECT_EQ("1", result[0]); + EXPECT_EQ("\"a\"", result[1]); +} + +#endif // GTEST_HAS_TR1_TUPLE + +#if GTEST_HAS_STD_TUPLE_ + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) { + Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple()); + EXPECT_EQ(0u, result.size()); +} + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) { + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::make_tuple(1)); + ASSERT_EQ(1u, result.size()); + EXPECT_EQ("1", result[0]); +} + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) { + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::make_tuple(1, 'a')); + ASSERT_EQ(2u, result.size()); + EXPECT_EQ("1", result[0]); + EXPECT_EQ("'a' (97, 0x61)", result[1]); +} + +TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) { + const int n = 1; + Strings result = UniversalTersePrintTupleFieldsToStrings( + ::std::tuple(n, "a")); + ASSERT_EQ(2u, result.size()); + EXPECT_EQ("1", result[0]); + EXPECT_EQ("\"a\"", result[1]); +} + +#endif // GTEST_HAS_STD_TUPLE_ + +#if GTEST_HAS_ABSL + +TEST(PrintOptionalTest, Basic) { + absl::optional value; + EXPECT_EQ("(nullopt)", PrintToString(value)); + value = {7}; + EXPECT_EQ("(7)", PrintToString(value)); + EXPECT_EQ("(1.1)", PrintToString(absl::optional{1.1})); + EXPECT_EQ("(\"A\")", PrintToString(absl::optional{"A"})); +} +#endif // GTEST_HAS_ABSL + +} // namespace gtest_printers_test +} // namespace testing diff --git a/googletest/test/googletest-tuple-test.cc b/googletest/test/googletest-tuple-test.cc new file mode 100644 index 0000000..bfaa3e0 --- /dev/null +++ b/googletest/test/googletest-tuple-test.cc @@ -0,0 +1,320 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +#include "gtest/internal/gtest-tuple.h" +#include +#include "gtest/gtest.h" + +namespace { + +using ::std::tr1::get; +using ::std::tr1::make_tuple; +using ::std::tr1::tuple; +using ::std::tr1::tuple_element; +using ::std::tr1::tuple_size; +using ::testing::StaticAssertTypeEq; + +// Tests that tuple_element >::type returns TK. +TEST(tuple_element_Test, ReturnsElementType) { + StaticAssertTypeEq >::type>(); + StaticAssertTypeEq >::type>(); + StaticAssertTypeEq >::type>(); +} + +// Tests that tuple_size::value gives the number of fields in tuple +// type T. +TEST(tuple_size_Test, ReturnsNumberOfFields) { + EXPECT_EQ(0, +tuple_size >::value); + EXPECT_EQ(1, +tuple_size >::value); + EXPECT_EQ(1, +tuple_size >::value); + EXPECT_EQ(1, +(tuple_size > >::value)); + EXPECT_EQ(2, +(tuple_size >::value)); + EXPECT_EQ(3, +(tuple_size >::value)); +} + +// Tests comparing a tuple with itself. +TEST(ComparisonTest, ComparesWithSelf) { + const tuple a(5, 'a', false); + + EXPECT_TRUE(a == a); + EXPECT_FALSE(a != a); +} + +// Tests comparing two tuples with the same value. +TEST(ComparisonTest, ComparesEqualTuples) { + const tuple a(5, true), b(5, true); + + EXPECT_TRUE(a == b); + EXPECT_FALSE(a != b); +} + +// Tests comparing two different tuples that have no reference fields. +TEST(ComparisonTest, ComparesUnequalTuplesWithoutReferenceFields) { + typedef tuple FooTuple; + + const FooTuple a(0, 'x'); + const FooTuple b(1, 'a'); + + EXPECT_TRUE(a != b); + EXPECT_FALSE(a == b); + + const FooTuple c(1, 'b'); + + EXPECT_TRUE(b != c); + EXPECT_FALSE(b == c); +} + +// Tests comparing two different tuples that have reference fields. +TEST(ComparisonTest, ComparesUnequalTuplesWithReferenceFields) { + typedef tuple FooTuple; + + int i = 5; + const char ch = 'a'; + const FooTuple a(i, ch); + + int j = 6; + const FooTuple b(j, ch); + + EXPECT_TRUE(a != b); + EXPECT_FALSE(a == b); + + j = 5; + const char ch2 = 'b'; + const FooTuple c(j, ch2); + + EXPECT_TRUE(b != c); + EXPECT_FALSE(b == c); +} + +// Tests that a tuple field with a reference type is an alias of the +// variable it's supposed to reference. +TEST(ReferenceFieldTest, IsAliasOfReferencedVariable) { + int n = 0; + tuple t(true, n); + + n = 1; + EXPECT_EQ(n, get<1>(t)) + << "Changing a underlying variable should update the reference field."; + + // Makes sure that the implementation doesn't do anything funny with + // the & operator for the return type of get<>(). + EXPECT_EQ(&n, &(get<1>(t))) + << "The address of a reference field should equal the address of " + << "the underlying variable."; + + get<1>(t) = 2; + EXPECT_EQ(2, n) + << "Changing a reference field should update the underlying variable."; +} + +// Tests that tuple's default constructor default initializes each field. +// This test needs to compile without generating warnings. +TEST(TupleConstructorTest, DefaultConstructorDefaultInitializesEachField) { + // The TR1 report requires that tuple's default constructor default + // initializes each field, even if it's a primitive type. If the + // implementation forgets to do this, this test will catch it by + // generating warnings about using uninitialized variables (assuming + // a decent compiler). + + tuple<> empty; + + tuple a1, b1; + b1 = a1; + EXPECT_EQ(0, get<0>(b1)); + + tuple a2, b2; + b2 = a2; + EXPECT_EQ(0, get<0>(b2)); + EXPECT_EQ(0.0, get<1>(b2)); + + tuple a3, b3; + b3 = a3; + EXPECT_EQ(0.0, get<0>(b3)); + EXPECT_EQ('\0', get<1>(b3)); + EXPECT_TRUE(get<2>(b3) == NULL); + + tuple a10, b10; + b10 = a10; + EXPECT_EQ(0, get<0>(b10)); + EXPECT_EQ(0, get<1>(b10)); + EXPECT_EQ(0, get<2>(b10)); + EXPECT_EQ(0, get<3>(b10)); + EXPECT_EQ(0, get<4>(b10)); + EXPECT_EQ(0, get<5>(b10)); + EXPECT_EQ(0, get<6>(b10)); + EXPECT_EQ(0, get<7>(b10)); + EXPECT_EQ(0, get<8>(b10)); + EXPECT_EQ(0, get<9>(b10)); +} + +// Tests constructing a tuple from its fields. +TEST(TupleConstructorTest, ConstructsFromFields) { + int n = 1; + // Reference field. + tuple a(n); + EXPECT_EQ(&n, &(get<0>(a))); + + // Non-reference fields. + tuple b(5, 'a'); + EXPECT_EQ(5, get<0>(b)); + EXPECT_EQ('a', get<1>(b)); + + // Const reference field. + const int m = 2; + tuple c(true, m); + EXPECT_TRUE(get<0>(c)); + EXPECT_EQ(&m, &(get<1>(c))); +} + +// Tests tuple's copy constructor. +TEST(TupleConstructorTest, CopyConstructor) { + tuple a(0.0, true); + tuple b(a); + + EXPECT_DOUBLE_EQ(0.0, get<0>(b)); + EXPECT_TRUE(get<1>(b)); +} + +// Tests constructing a tuple from another tuple that has a compatible +// but different type. +TEST(TupleConstructorTest, ConstructsFromDifferentTupleType) { + tuple a(0, 1, 'a'); + tuple b(a); + + EXPECT_DOUBLE_EQ(0.0, get<0>(b)); + EXPECT_EQ(1, get<1>(b)); + EXPECT_EQ('a', get<2>(b)); +} + +// Tests constructing a 2-tuple from an std::pair. +TEST(TupleConstructorTest, ConstructsFromPair) { + ::std::pair a(1, 'a'); + tuple b(a); + tuple c(a); +} + +// Tests assigning a tuple to another tuple with the same type. +TEST(TupleAssignmentTest, AssignsToSameTupleType) { + const tuple a(5, 7L); + tuple b; + b = a; + EXPECT_EQ(5, get<0>(b)); + EXPECT_EQ(7L, get<1>(b)); +} + +// Tests assigning a tuple to another tuple with a different but +// compatible type. +TEST(TupleAssignmentTest, AssignsToDifferentTupleType) { + const tuple a(1, 7L, true); + tuple b; + b = a; + EXPECT_EQ(1L, get<0>(b)); + EXPECT_EQ(7, get<1>(b)); + EXPECT_TRUE(get<2>(b)); +} + +// Tests assigning an std::pair to a 2-tuple. +TEST(TupleAssignmentTest, AssignsFromPair) { + const ::std::pair a(5, true); + tuple b; + b = a; + EXPECT_EQ(5, get<0>(b)); + EXPECT_TRUE(get<1>(b)); + + tuple c; + c = a; + EXPECT_EQ(5L, get<0>(c)); + EXPECT_TRUE(get<1>(c)); +} + +// A fixture for testing big tuples. +class BigTupleTest : public testing::Test { + protected: + typedef tuple BigTuple; + + BigTupleTest() : + a_(1, 0, 0, 0, 0, 0, 0, 0, 0, 2), + b_(1, 0, 0, 0, 0, 0, 0, 0, 0, 3) {} + + BigTuple a_, b_; +}; + +// Tests constructing big tuples. +TEST_F(BigTupleTest, Construction) { + BigTuple a; + BigTuple b(b_); +} + +// Tests that get(t) returns the N-th (0-based) field of tuple t. +TEST_F(BigTupleTest, get) { + EXPECT_EQ(1, get<0>(a_)); + EXPECT_EQ(2, get<9>(a_)); + + // Tests that get() works on a const tuple too. + const BigTuple a(a_); + EXPECT_EQ(1, get<0>(a)); + EXPECT_EQ(2, get<9>(a)); +} + +// Tests comparing big tuples. +TEST_F(BigTupleTest, Comparisons) { + EXPECT_TRUE(a_ == a_); + EXPECT_FALSE(a_ != a_); + + EXPECT_TRUE(a_ != b_); + EXPECT_FALSE(a_ == b_); +} + +TEST(MakeTupleTest, WorksForScalarTypes) { + tuple a; + a = make_tuple(true, 5); + EXPECT_TRUE(get<0>(a)); + EXPECT_EQ(5, get<1>(a)); + + tuple b; + b = make_tuple('a', 'b', 5); + EXPECT_EQ('a', get<0>(b)); + EXPECT_EQ('b', get<1>(b)); + EXPECT_EQ(5, get<2>(b)); +} + +TEST(MakeTupleTest, WorksForPointers) { + int a[] = { 1, 2, 3, 4 }; + const char* const str = "hi"; + int* const p = a; + + tuple t; + t = make_tuple(str, p); + EXPECT_EQ(str, get<0>(t)); + EXPECT_EQ(p, get<1>(t)); +} + +} // namespace diff --git a/googletest/test/gtest-message_test.cc b/googletest/test/gtest-message_test.cc deleted file mode 100644 index 175238e..0000000 --- a/googletest/test/gtest-message_test.cc +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) -// -// Tests for the Message class. - -#include "gtest/gtest-message.h" - -#include "gtest/gtest.h" - -namespace { - -using ::testing::Message; - -// Tests the testing::Message class - -// Tests the default constructor. -TEST(MessageTest, DefaultConstructor) { - const Message msg; - EXPECT_EQ("", msg.GetString()); -} - -// Tests the copy constructor. -TEST(MessageTest, CopyConstructor) { - const Message msg1("Hello"); - const Message msg2(msg1); - EXPECT_EQ("Hello", msg2.GetString()); -} - -// Tests constructing a Message from a C-string. -TEST(MessageTest, ConstructsFromCString) { - Message msg("Hello"); - EXPECT_EQ("Hello", msg.GetString()); -} - -// Tests streaming a float. -TEST(MessageTest, StreamsFloat) { - const std::string s = (Message() << 1.23456F << " " << 2.34567F).GetString(); - // Both numbers should be printed with enough precision. - EXPECT_PRED_FORMAT2(testing::IsSubstring, "1.234560", s.c_str()); - EXPECT_PRED_FORMAT2(testing::IsSubstring, " 2.345669", s.c_str()); -} - -// Tests streaming a double. -TEST(MessageTest, StreamsDouble) { - const std::string s = (Message() << 1260570880.4555497 << " " - << 1260572265.1954534).GetString(); - // Both numbers should be printed with enough precision. - EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str()); - EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str()); -} - -// Tests streaming a non-char pointer. -TEST(MessageTest, StreamsPointer) { - int n = 0; - int* p = &n; - EXPECT_NE("(null)", (Message() << p).GetString()); -} - -// Tests streaming a NULL non-char pointer. -TEST(MessageTest, StreamsNullPointer) { - int* p = NULL; - EXPECT_EQ("(null)", (Message() << p).GetString()); -} - -// Tests streaming a C string. -TEST(MessageTest, StreamsCString) { - EXPECT_EQ("Foo", (Message() << "Foo").GetString()); -} - -// Tests streaming a NULL C string. -TEST(MessageTest, StreamsNullCString) { - char* p = NULL; - EXPECT_EQ("(null)", (Message() << p).GetString()); -} - -// Tests streaming std::string. -TEST(MessageTest, StreamsString) { - const ::std::string str("Hello"); - EXPECT_EQ("Hello", (Message() << str).GetString()); -} - -// Tests that we can output strings containing embedded NULs. -TEST(MessageTest, StreamsStringWithEmbeddedNUL) { - const char char_array_with_nul[] = - "Here's a NUL\0 and some more string"; - const ::std::string string_with_nul(char_array_with_nul, - sizeof(char_array_with_nul) - 1); - EXPECT_EQ("Here's a NUL\\0 and some more string", - (Message() << string_with_nul).GetString()); -} - -// Tests streaming a NUL char. -TEST(MessageTest, StreamsNULChar) { - EXPECT_EQ("\\0", (Message() << '\0').GetString()); -} - -// Tests streaming int. -TEST(MessageTest, StreamsInt) { - EXPECT_EQ("123", (Message() << 123).GetString()); -} - -// Tests that basic IO manipulators (endl, ends, and flush) can be -// streamed to Message. -TEST(MessageTest, StreamsBasicIoManip) { - EXPECT_EQ("Line 1.\nA NUL char \\0 in line 2.", - (Message() << "Line 1." << std::endl - << "A NUL char " << std::ends << std::flush - << " in line 2.").GetString()); -} - -// Tests Message::GetString() -TEST(MessageTest, GetString) { - Message msg; - msg << 1 << " lamb"; - EXPECT_EQ("1 lamb", msg.GetString()); -} - -// Tests streaming a Message object to an ostream. -TEST(MessageTest, StreamsToOStream) { - Message msg("Hello"); - ::std::stringstream ss; - ss << msg; - EXPECT_EQ("Hello", testing::internal::StringStreamToString(&ss)); -} - -// Tests that a Message object doesn't take up too much stack space. -TEST(MessageTest, DoesNotTakeUpMuchStackSpace) { - EXPECT_LE(sizeof(Message), 16U); -} - -} // namespace diff --git a/googletest/test/gtest-options_test.cc b/googletest/test/gtest-options_test.cc deleted file mode 100644 index 10cb1df..0000000 --- a/googletest/test/gtest-options_test.cc +++ /dev/null @@ -1,213 +0,0 @@ -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// -// Google Test UnitTestOptions tests -// -// This file tests classes and functions used internally by -// Google Test. They are subject to change without notice. -// -// This file is #included from gtest.cc, to avoid changing build or -// make-files on Windows and other platforms. Do not #include this file -// anywhere else! - -#include "gtest/gtest.h" - -#if GTEST_OS_WINDOWS_MOBILE -# include -#elif GTEST_OS_WINDOWS -# include -#endif // GTEST_OS_WINDOWS_MOBILE - -#include "src/gtest-internal-inl.h" - -namespace testing { -namespace internal { -namespace { - -// Turns the given relative path into an absolute path. -FilePath GetAbsolutePathOf(const FilePath& relative_path) { - return FilePath::ConcatPaths(FilePath::GetCurrentDir(), relative_path); -} - -// Testing UnitTestOptions::GetOutputFormat/GetOutputFile. - -TEST(XmlOutputTest, GetOutputFormatDefault) { - GTEST_FLAG(output) = ""; - EXPECT_STREQ("", UnitTestOptions::GetOutputFormat().c_str()); -} - -TEST(XmlOutputTest, GetOutputFormat) { - GTEST_FLAG(output) = "xml:filename"; - EXPECT_STREQ("xml", UnitTestOptions::GetOutputFormat().c_str()); -} - -TEST(XmlOutputTest, GetOutputFileDefault) { - GTEST_FLAG(output) = ""; - EXPECT_EQ(GetAbsolutePathOf(FilePath("test_detail.xml")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -} - -TEST(XmlOutputTest, GetOutputFileSingleFile) { - GTEST_FLAG(output) = "xml:filename.abc"; - EXPECT_EQ(GetAbsolutePathOf(FilePath("filename.abc")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -} - -TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) { - GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_; - const std::string expected_output_file = - GetAbsolutePathOf( - FilePath(std::string("path") + GTEST_PATH_SEP_ + - GetCurrentExecutableName().string() + ".xml")).string(); - const std::string& output_file = - UnitTestOptions::GetAbsolutePathToOutputFile(); -#if GTEST_OS_WINDOWS - EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); -#else - EXPECT_EQ(expected_output_file, output_file.c_str()); -#endif -} - -TEST(OutputFileHelpersTest, GetCurrentExecutableName) { - const std::string exe_str = GetCurrentExecutableName().string(); -#if GTEST_OS_WINDOWS - const bool success = - _strcmpi("gtest-options_test", exe_str.c_str()) == 0 || - _strcmpi("gtest-options-ex_test", exe_str.c_str()) == 0 || - _strcmpi("gtest_all_test", exe_str.c_str()) == 0 || - _strcmpi("gtest_dll_test", exe_str.c_str()) == 0; -#elif GTEST_OS_FUCHSIA - const bool success = exe_str == "app"; -#else - // TODO(wan@google.com): remove the hard-coded "lt-" prefix when - // Chandler Carruth's libtool replacement is ready. - const bool success = - exe_str == "gtest-options_test" || - exe_str == "gtest_all_test" || - exe_str == "lt-gtest_all_test" || - exe_str == "gtest_dll_test"; -#endif // GTEST_OS_WINDOWS - if (!success) - FAIL() << "GetCurrentExecutableName() returns " << exe_str; -} - -#if !GTEST_OS_FUCHSIA - -class XmlOutputChangeDirTest : public Test { - protected: - virtual void SetUp() { - original_working_dir_ = FilePath::GetCurrentDir(); - posix::ChDir(".."); - // This will make the test fail if run from the root directory. - EXPECT_NE(original_working_dir_.string(), - FilePath::GetCurrentDir().string()); - } - - virtual void TearDown() { - posix::ChDir(original_working_dir_.string().c_str()); - } - - FilePath original_working_dir_; -}; - -TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) { - GTEST_FLAG(output) = ""; - EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, - FilePath("test_detail.xml")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -} - -TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) { - GTEST_FLAG(output) = "xml"; - EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, - FilePath("test_detail.xml")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -} - -TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) { - GTEST_FLAG(output) = "xml:filename.abc"; - EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, - FilePath("filename.abc")).string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -} - -TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { - GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_; - const std::string expected_output_file = - FilePath::ConcatPaths( - original_working_dir_, - FilePath(std::string("path") + GTEST_PATH_SEP_ + - GetCurrentExecutableName().string() + ".xml")).string(); - const std::string& output_file = - UnitTestOptions::GetAbsolutePathToOutputFile(); -#if GTEST_OS_WINDOWS - EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); -#else - EXPECT_EQ(expected_output_file, output_file.c_str()); -#endif -} - -TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) { -#if GTEST_OS_WINDOWS - GTEST_FLAG(output) = "xml:c:\\tmp\\filename.abc"; - EXPECT_EQ(FilePath("c:\\tmp\\filename.abc").string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -#else - GTEST_FLAG(output) ="xml:/tmp/filename.abc"; - EXPECT_EQ(FilePath("/tmp/filename.abc").string(), - UnitTestOptions::GetAbsolutePathToOutputFile()); -#endif -} - -TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) { -#if GTEST_OS_WINDOWS - const std::string path = "c:\\tmp\\"; -#else - const std::string path = "/tmp/"; -#endif - - GTEST_FLAG(output) = "xml:" + path; - const std::string expected_output_file = - path + GetCurrentExecutableName().string() + ".xml"; - const std::string& output_file = - UnitTestOptions::GetAbsolutePathToOutputFile(); - -#if GTEST_OS_WINDOWS - EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str()); -#else - EXPECT_EQ(expected_output_file, output_file.c_str()); -#endif -} - -#endif // !GTEST_OS_FUCHSIA - -} // namespace -} // namespace internal -} // namespace testing diff --git a/googletest/test/gtest-port_test.cc b/googletest/test/gtest-port_test.cc deleted file mode 100644 index 3801e5e..0000000 --- a/googletest/test/gtest-port_test.cc +++ /dev/null @@ -1,1303 +0,0 @@ -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Authors: vladl@google.com (Vlad Losev), wan@google.com (Zhanyong Wan) -// -// This file tests the internal cross-platform support utilities. - -#include "gtest/internal/gtest-port.h" - -#include - -#if GTEST_OS_MAC -# include -#endif // GTEST_OS_MAC - -#include -#include // For std::pair and std::make_pair. -#include - -#include "gtest/gtest.h" -#include "gtest/gtest-spi.h" -#include "src/gtest-internal-inl.h" - -using std::make_pair; -using std::pair; - -namespace testing { -namespace internal { - -TEST(IsXDigitTest, WorksForNarrowAscii) { - EXPECT_TRUE(IsXDigit('0')); - EXPECT_TRUE(IsXDigit('9')); - EXPECT_TRUE(IsXDigit('A')); - EXPECT_TRUE(IsXDigit('F')); - EXPECT_TRUE(IsXDigit('a')); - EXPECT_TRUE(IsXDigit('f')); - - EXPECT_FALSE(IsXDigit('-')); - EXPECT_FALSE(IsXDigit('g')); - EXPECT_FALSE(IsXDigit('G')); -} - -TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) { - EXPECT_FALSE(IsXDigit(static_cast('\x80'))); - EXPECT_FALSE(IsXDigit(static_cast('0' | '\x80'))); -} - -TEST(IsXDigitTest, WorksForWideAscii) { - EXPECT_TRUE(IsXDigit(L'0')); - EXPECT_TRUE(IsXDigit(L'9')); - EXPECT_TRUE(IsXDigit(L'A')); - EXPECT_TRUE(IsXDigit(L'F')); - EXPECT_TRUE(IsXDigit(L'a')); - EXPECT_TRUE(IsXDigit(L'f')); - - EXPECT_FALSE(IsXDigit(L'-')); - EXPECT_FALSE(IsXDigit(L'g')); - EXPECT_FALSE(IsXDigit(L'G')); -} - -TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) { - EXPECT_FALSE(IsXDigit(static_cast(0x80))); - EXPECT_FALSE(IsXDigit(static_cast(L'0' | 0x80))); - EXPECT_FALSE(IsXDigit(static_cast(L'0' | 0x100))); -} - -class Base { - public: - // Copy constructor and assignment operator do exactly what we need, so we - // use them. - Base() : member_(0) {} - explicit Base(int n) : member_(n) {} - virtual ~Base() {} - int member() { return member_; } - - private: - int member_; -}; - -class Derived : public Base { - public: - explicit Derived(int n) : Base(n) {} -}; - -TEST(ImplicitCastTest, ConvertsPointers) { - Derived derived(0); - EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_(&derived)); -} - -TEST(ImplicitCastTest, CanUseInheritance) { - Derived derived(1); - Base base = ::testing::internal::ImplicitCast_(derived); - EXPECT_EQ(derived.member(), base.member()); -} - -class Castable { - public: - explicit Castable(bool* converted) : converted_(converted) {} - operator Base() { - *converted_ = true; - return Base(); - } - - private: - bool* converted_; -}; - -TEST(ImplicitCastTest, CanUseNonConstCastOperator) { - bool converted = false; - Castable castable(&converted); - Base base = ::testing::internal::ImplicitCast_(castable); - EXPECT_TRUE(converted); -} - -class ConstCastable { - public: - explicit ConstCastable(bool* converted) : converted_(converted) {} - operator Base() const { - *converted_ = true; - return Base(); - } - - private: - bool* converted_; -}; - -TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) { - bool converted = false; - const ConstCastable const_castable(&converted); - Base base = ::testing::internal::ImplicitCast_(const_castable); - EXPECT_TRUE(converted); -} - -class ConstAndNonConstCastable { - public: - ConstAndNonConstCastable(bool* converted, bool* const_converted) - : converted_(converted), const_converted_(const_converted) {} - operator Base() { - *converted_ = true; - return Base(); - } - operator Base() const { - *const_converted_ = true; - return Base(); - } - - private: - bool* converted_; - bool* const_converted_; -}; - -TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) { - bool converted = false; - bool const_converted = false; - ConstAndNonConstCastable castable(&converted, &const_converted); - Base base = ::testing::internal::ImplicitCast_(castable); - EXPECT_TRUE(converted); - EXPECT_FALSE(const_converted); - - converted = false; - const_converted = false; - const ConstAndNonConstCastable const_castable(&converted, &const_converted); - base = ::testing::internal::ImplicitCast_(const_castable); - EXPECT_FALSE(converted); - EXPECT_TRUE(const_converted); -} - -class To { - public: - To(bool* converted) { *converted = true; } // NOLINT -}; - -TEST(ImplicitCastTest, CanUseImplicitConstructor) { - bool converted = false; - To to = ::testing::internal::ImplicitCast_(&converted); - (void)to; - EXPECT_TRUE(converted); -} - -TEST(IteratorTraitsTest, WorksForSTLContainerIterators) { - StaticAssertTypeEq::const_iterator>::value_type>(); - StaticAssertTypeEq::iterator>::value_type>(); -} - -TEST(IteratorTraitsTest, WorksForPointerToNonConst) { - StaticAssertTypeEq::value_type>(); - StaticAssertTypeEq::value_type>(); -} - -TEST(IteratorTraitsTest, WorksForPointerToConst) { - StaticAssertTypeEq::value_type>(); - StaticAssertTypeEq::value_type>(); -} - -// Tests that the element_type typedef is available in scoped_ptr and refers -// to the parameter type. -TEST(ScopedPtrTest, DefinesElementType) { - StaticAssertTypeEq::element_type>(); -} - -// TODO(vladl@google.com): Implement THE REST of scoped_ptr tests. - -TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) { - if (AlwaysFalse()) - GTEST_CHECK_(false) << "This should never be executed; " - "It's a compilation test only."; - - if (AlwaysTrue()) - GTEST_CHECK_(true); - else - ; // NOLINT - - if (AlwaysFalse()) - ; // NOLINT - else - GTEST_CHECK_(true) << ""; -} - -TEST(GtestCheckSyntaxTest, WorksWithSwitch) { - switch (0) { - case 1: - break; - default: - GTEST_CHECK_(true); - } - - switch (0) - case 0: - GTEST_CHECK_(true) << "Check failed in switch case"; -} - -// Verifies behavior of FormatFileLocation. -TEST(FormatFileLocationTest, FormatsFileLocation) { - EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42)); - EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42)); -} - -TEST(FormatFileLocationTest, FormatsUnknownFile) { - EXPECT_PRED_FORMAT2( - IsSubstring, "unknown file", FormatFileLocation(NULL, 42)); - EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(NULL, 42)); -} - -TEST(FormatFileLocationTest, FormatsUknownLine) { - EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1)); -} - -TEST(FormatFileLocationTest, FormatsUknownFileAndLine) { - EXPECT_EQ("unknown file:", FormatFileLocation(NULL, -1)); -} - -// Verifies behavior of FormatCompilerIndependentFileLocation. -TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) { - EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42)); -} - -TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) { - EXPECT_EQ("unknown file:42", - FormatCompilerIndependentFileLocation(NULL, 42)); -} - -TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) { - EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1)); -} - -TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) { - EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1)); -} - -#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA -void* ThreadFunc(void* data) { - internal::Mutex* mutex = static_cast(data); - mutex->Lock(); - mutex->Unlock(); - return NULL; -} - -TEST(GetThreadCountTest, ReturnsCorrectValue) { - const size_t starting_count = GetThreadCount(); - pthread_t thread_id; - - internal::Mutex mutex; - { - internal::MutexLock lock(&mutex); - pthread_attr_t attr; - ASSERT_EQ(0, pthread_attr_init(&attr)); - ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); - - const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex); - ASSERT_EQ(0, pthread_attr_destroy(&attr)); - ASSERT_EQ(0, status); - EXPECT_EQ(starting_count + 1, GetThreadCount()); - } - - void* dummy; - ASSERT_EQ(0, pthread_join(thread_id, &dummy)); - - // The OS may not immediately report the updated thread count after - // joining a thread, causing flakiness in this test. To counter that, we - // wait for up to .5 seconds for the OS to report the correct value. - for (int i = 0; i < 5; ++i) { - if (GetThreadCount() == starting_count) - break; - - SleepMilliseconds(100); - } - - EXPECT_EQ(starting_count, GetThreadCount()); -} -#else -TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) { - EXPECT_EQ(0U, GetThreadCount()); -} -#endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA - -TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { - const bool a_false_condition = false; - const char regex[] = -#ifdef _MSC_VER - "gtest-port_test\\.cc\\(\\d+\\):" -#elif GTEST_USES_POSIX_RE - "gtest-port_test\\.cc:[0-9]+" -#else - "gtest-port_test\\.cc:\\d+" -#endif // _MSC_VER - ".*a_false_condition.*Extra info.*"; - - EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info", - regex); -} - -#if GTEST_HAS_DEATH_TEST - -TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { - EXPECT_EXIT({ - GTEST_CHECK_(true) << "Extra info"; - ::std::cerr << "Success\n"; - exit(0); }, - ::testing::ExitedWithCode(0), "Success"); -} - -#endif // GTEST_HAS_DEATH_TEST - -// Verifies that Google Test choose regular expression engine appropriate to -// the platform. The test will produce compiler errors in case of failure. -// For simplicity, we only cover the most important platforms here. -TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) { -#if !GTEST_USES_PCRE -# if GTEST_HAS_POSIX_RE - - EXPECT_TRUE(GTEST_USES_POSIX_RE); - -# else - - EXPECT_TRUE(GTEST_USES_SIMPLE_RE); - -# endif -#endif // !GTEST_USES_PCRE -} - -#if GTEST_USES_POSIX_RE - -# if GTEST_HAS_TYPED_TEST - -template -class RETest : public ::testing::Test {}; - -// Defines StringTypes as the list of all string types that class RE -// supports. -typedef testing::Types< - ::std::string, -# if GTEST_HAS_GLOBAL_STRING - ::string, -# endif // GTEST_HAS_GLOBAL_STRING - const char*> StringTypes; - -TYPED_TEST_CASE(RETest, StringTypes); - -// Tests RE's implicit constructors. -TYPED_TEST(RETest, ImplicitConstructorWorks) { - const RE empty(TypeParam("")); - EXPECT_STREQ("", empty.pattern()); - - const RE simple(TypeParam("hello")); - EXPECT_STREQ("hello", simple.pattern()); - - const RE normal(TypeParam(".*(\\w+)")); - EXPECT_STREQ(".*(\\w+)", normal.pattern()); -} - -// Tests that RE's constructors reject invalid regular expressions. -TYPED_TEST(RETest, RejectsInvalidRegex) { - EXPECT_NONFATAL_FAILURE({ - const RE invalid(TypeParam("?")); - }, "\"?\" is not a valid POSIX Extended regular expression."); -} - -// Tests RE::FullMatch(). -TYPED_TEST(RETest, FullMatchWorks) { - const RE empty(TypeParam("")); - EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty)); - EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty)); - - const RE re(TypeParam("a.*z")); - EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re)); - EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re)); - EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re)); - EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re)); -} - -// Tests RE::PartialMatch(). -TYPED_TEST(RETest, PartialMatchWorks) { - const RE empty(TypeParam("")); - EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty)); - EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty)); - - const RE re(TypeParam("a.*z")); - EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re)); - EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re)); - EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re)); - EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re)); - EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re)); -} - -# endif // GTEST_HAS_TYPED_TEST - -#elif GTEST_USES_SIMPLE_RE - -TEST(IsInSetTest, NulCharIsNotInAnySet) { - EXPECT_FALSE(IsInSet('\0', "")); - EXPECT_FALSE(IsInSet('\0', "\0")); - EXPECT_FALSE(IsInSet('\0', "a")); -} - -TEST(IsInSetTest, WorksForNonNulChars) { - EXPECT_FALSE(IsInSet('a', "Ab")); - EXPECT_FALSE(IsInSet('c', "")); - - EXPECT_TRUE(IsInSet('b', "bcd")); - EXPECT_TRUE(IsInSet('b', "ab")); -} - -TEST(IsAsciiDigitTest, IsFalseForNonDigit) { - EXPECT_FALSE(IsAsciiDigit('\0')); - EXPECT_FALSE(IsAsciiDigit(' ')); - EXPECT_FALSE(IsAsciiDigit('+')); - EXPECT_FALSE(IsAsciiDigit('-')); - EXPECT_FALSE(IsAsciiDigit('.')); - EXPECT_FALSE(IsAsciiDigit('a')); -} - -TEST(IsAsciiDigitTest, IsTrueForDigit) { - EXPECT_TRUE(IsAsciiDigit('0')); - EXPECT_TRUE(IsAsciiDigit('1')); - EXPECT_TRUE(IsAsciiDigit('5')); - EXPECT_TRUE(IsAsciiDigit('9')); -} - -TEST(IsAsciiPunctTest, IsFalseForNonPunct) { - EXPECT_FALSE(IsAsciiPunct('\0')); - EXPECT_FALSE(IsAsciiPunct(' ')); - EXPECT_FALSE(IsAsciiPunct('\n')); - EXPECT_FALSE(IsAsciiPunct('a')); - EXPECT_FALSE(IsAsciiPunct('0')); -} - -TEST(IsAsciiPunctTest, IsTrueForPunct) { - for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) { - EXPECT_PRED1(IsAsciiPunct, *p); - } -} - -TEST(IsRepeatTest, IsFalseForNonRepeatChar) { - EXPECT_FALSE(IsRepeat('\0')); - EXPECT_FALSE(IsRepeat(' ')); - EXPECT_FALSE(IsRepeat('a')); - EXPECT_FALSE(IsRepeat('1')); - EXPECT_FALSE(IsRepeat('-')); -} - -TEST(IsRepeatTest, IsTrueForRepeatChar) { - EXPECT_TRUE(IsRepeat('?')); - EXPECT_TRUE(IsRepeat('*')); - EXPECT_TRUE(IsRepeat('+')); -} - -TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) { - EXPECT_FALSE(IsAsciiWhiteSpace('\0')); - EXPECT_FALSE(IsAsciiWhiteSpace('a')); - EXPECT_FALSE(IsAsciiWhiteSpace('1')); - EXPECT_FALSE(IsAsciiWhiteSpace('+')); - EXPECT_FALSE(IsAsciiWhiteSpace('_')); -} - -TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) { - EXPECT_TRUE(IsAsciiWhiteSpace(' ')); - EXPECT_TRUE(IsAsciiWhiteSpace('\n')); - EXPECT_TRUE(IsAsciiWhiteSpace('\r')); - EXPECT_TRUE(IsAsciiWhiteSpace('\t')); - EXPECT_TRUE(IsAsciiWhiteSpace('\v')); - EXPECT_TRUE(IsAsciiWhiteSpace('\f')); -} - -TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) { - EXPECT_FALSE(IsAsciiWordChar('\0')); - EXPECT_FALSE(IsAsciiWordChar('+')); - EXPECT_FALSE(IsAsciiWordChar('.')); - EXPECT_FALSE(IsAsciiWordChar(' ')); - EXPECT_FALSE(IsAsciiWordChar('\n')); -} - -TEST(IsAsciiWordCharTest, IsTrueForLetter) { - EXPECT_TRUE(IsAsciiWordChar('a')); - EXPECT_TRUE(IsAsciiWordChar('b')); - EXPECT_TRUE(IsAsciiWordChar('A')); - EXPECT_TRUE(IsAsciiWordChar('Z')); -} - -TEST(IsAsciiWordCharTest, IsTrueForDigit) { - EXPECT_TRUE(IsAsciiWordChar('0')); - EXPECT_TRUE(IsAsciiWordChar('1')); - EXPECT_TRUE(IsAsciiWordChar('7')); - EXPECT_TRUE(IsAsciiWordChar('9')); -} - -TEST(IsAsciiWordCharTest, IsTrueForUnderscore) { - EXPECT_TRUE(IsAsciiWordChar('_')); -} - -TEST(IsValidEscapeTest, IsFalseForNonPrintable) { - EXPECT_FALSE(IsValidEscape('\0')); - EXPECT_FALSE(IsValidEscape('\007')); -} - -TEST(IsValidEscapeTest, IsFalseForDigit) { - EXPECT_FALSE(IsValidEscape('0')); - EXPECT_FALSE(IsValidEscape('9')); -} - -TEST(IsValidEscapeTest, IsFalseForWhiteSpace) { - EXPECT_FALSE(IsValidEscape(' ')); - EXPECT_FALSE(IsValidEscape('\n')); -} - -TEST(IsValidEscapeTest, IsFalseForSomeLetter) { - EXPECT_FALSE(IsValidEscape('a')); - EXPECT_FALSE(IsValidEscape('Z')); -} - -TEST(IsValidEscapeTest, IsTrueForPunct) { - EXPECT_TRUE(IsValidEscape('.')); - EXPECT_TRUE(IsValidEscape('-')); - EXPECT_TRUE(IsValidEscape('^')); - EXPECT_TRUE(IsValidEscape('$')); - EXPECT_TRUE(IsValidEscape('(')); - EXPECT_TRUE(IsValidEscape(']')); - EXPECT_TRUE(IsValidEscape('{')); - EXPECT_TRUE(IsValidEscape('|')); -} - -TEST(IsValidEscapeTest, IsTrueForSomeLetter) { - EXPECT_TRUE(IsValidEscape('d')); - EXPECT_TRUE(IsValidEscape('D')); - EXPECT_TRUE(IsValidEscape('s')); - EXPECT_TRUE(IsValidEscape('S')); - EXPECT_TRUE(IsValidEscape('w')); - EXPECT_TRUE(IsValidEscape('W')); -} - -TEST(AtomMatchesCharTest, EscapedPunct) { - EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, '\\', ' ')); - EXPECT_FALSE(AtomMatchesChar(true, '_', '.')); - EXPECT_FALSE(AtomMatchesChar(true, '.', 'a')); - - EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\')); - EXPECT_TRUE(AtomMatchesChar(true, '_', '_')); - EXPECT_TRUE(AtomMatchesChar(true, '+', '+')); - EXPECT_TRUE(AtomMatchesChar(true, '.', '.')); -} - -TEST(AtomMatchesCharTest, Escaped_d) { - EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a')); - EXPECT_FALSE(AtomMatchesChar(true, 'd', '.')); - - EXPECT_TRUE(AtomMatchesChar(true, 'd', '0')); - EXPECT_TRUE(AtomMatchesChar(true, 'd', '9')); -} - -TEST(AtomMatchesCharTest, Escaped_D) { - EXPECT_FALSE(AtomMatchesChar(true, 'D', '0')); - EXPECT_FALSE(AtomMatchesChar(true, 'D', '9')); - - EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0')); - EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a')); - EXPECT_TRUE(AtomMatchesChar(true, 'D', '-')); -} - -TEST(AtomMatchesCharTest, Escaped_s) { - EXPECT_FALSE(AtomMatchesChar(true, 's', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 's', 'a')); - EXPECT_FALSE(AtomMatchesChar(true, 's', '.')); - EXPECT_FALSE(AtomMatchesChar(true, 's', '9')); - - EXPECT_TRUE(AtomMatchesChar(true, 's', ' ')); - EXPECT_TRUE(AtomMatchesChar(true, 's', '\n')); - EXPECT_TRUE(AtomMatchesChar(true, 's', '\t')); -} - -TEST(AtomMatchesCharTest, Escaped_S) { - EXPECT_FALSE(AtomMatchesChar(true, 'S', ' ')); - EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r')); - - EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0')); - EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a')); - EXPECT_TRUE(AtomMatchesChar(true, 'S', '9')); -} - -TEST(AtomMatchesCharTest, Escaped_w) { - EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 'w', '+')); - EXPECT_FALSE(AtomMatchesChar(true, 'w', ' ')); - EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n')); - - EXPECT_TRUE(AtomMatchesChar(true, 'w', '0')); - EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b')); - EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C')); - EXPECT_TRUE(AtomMatchesChar(true, 'w', '_')); -} - -TEST(AtomMatchesCharTest, Escaped_W) { - EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A')); - EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b')); - EXPECT_FALSE(AtomMatchesChar(true, 'W', '9')); - EXPECT_FALSE(AtomMatchesChar(true, 'W', '_')); - - EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0')); - EXPECT_TRUE(AtomMatchesChar(true, 'W', '*')); - EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n')); -} - -TEST(AtomMatchesCharTest, EscapedWhiteSpace) { - EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n')); - EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r')); - EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a')); - EXPECT_FALSE(AtomMatchesChar(true, 't', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 't', 't')); - EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0')); - EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f')); - - EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f')); - EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n')); - EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r')); - EXPECT_TRUE(AtomMatchesChar(true, 't', '\t')); - EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v')); -} - -TEST(AtomMatchesCharTest, UnescapedDot) { - EXPECT_FALSE(AtomMatchesChar(false, '.', '\n')); - - EXPECT_TRUE(AtomMatchesChar(false, '.', '\0')); - EXPECT_TRUE(AtomMatchesChar(false, '.', '.')); - EXPECT_TRUE(AtomMatchesChar(false, '.', 'a')); - EXPECT_TRUE(AtomMatchesChar(false, '.', ' ')); -} - -TEST(AtomMatchesCharTest, UnescapedChar) { - EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0')); - EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b')); - EXPECT_FALSE(AtomMatchesChar(false, '$', 'a')); - - EXPECT_TRUE(AtomMatchesChar(false, '$', '$')); - EXPECT_TRUE(AtomMatchesChar(false, '5', '5')); - EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z')); -} - -TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) { - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)), - "NULL is not a valid simple regular expression"); - EXPECT_NONFATAL_FAILURE( - ASSERT_FALSE(ValidateRegex("a\\")), - "Syntax error at index 1 in simple regular expression \"a\\\": "); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")), - "'\\' cannot appear at the end"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")), - "'\\' cannot appear at the end"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")), - "invalid escape sequence \"\\h\""); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")), - "'^' can only appear at the beginning"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")), - "'^' can only appear at the beginning"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")), - "'$' can only appear at the end"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")), - "'$' can only appear at the end"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")), - "'(' is unsupported"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")), - "')' is unsupported"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")), - "'[' is unsupported"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")), - "'{' is unsupported"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")), - "'?' can only follow a repeatable token"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")), - "'*' can only follow a repeatable token"); - EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")), - "'+' can only follow a repeatable token"); -} - -TEST(ValidateRegexTest, ReturnsTrueForValid) { - EXPECT_TRUE(ValidateRegex("")); - EXPECT_TRUE(ValidateRegex("a")); - EXPECT_TRUE(ValidateRegex(".*")); - EXPECT_TRUE(ValidateRegex("^a_+")); - EXPECT_TRUE(ValidateRegex("^a\\t\\&?")); - EXPECT_TRUE(ValidateRegex("09*$")); - EXPECT_TRUE(ValidateRegex("^Z$")); - EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}")); -} - -TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) { - EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba")); - // Repeating more than once. - EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab")); - - // Repeating zero times. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba")); - // Repeating once. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab")); - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##")); -} - -TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) { - EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab")); - - // Repeating zero times. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc")); - // Repeating once. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc")); - // Repeating more than once. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g")); -} - -TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) { - EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab")); - // Repeating zero times. - EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc")); - - // Repeating once. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc")); - // Repeating more than once. - EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g")); -} - -TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) { - EXPECT_TRUE(MatchRegexAtHead("", "")); - EXPECT_TRUE(MatchRegexAtHead("", "ab")); -} - -TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) { - EXPECT_FALSE(MatchRegexAtHead("$", "a")); - - EXPECT_TRUE(MatchRegexAtHead("$", "")); - EXPECT_TRUE(MatchRegexAtHead("a$", "a")); -} - -TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) { - EXPECT_FALSE(MatchRegexAtHead("\\w", "+")); - EXPECT_FALSE(MatchRegexAtHead("\\W", "ab")); - - EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab")); - EXPECT_TRUE(MatchRegexAtHead("\\d", "1a")); -} - -TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) { - EXPECT_FALSE(MatchRegexAtHead(".+a", "abc")); - EXPECT_FALSE(MatchRegexAtHead("a?b", "aab")); - - EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab")); - EXPECT_TRUE(MatchRegexAtHead("a?b", "b")); - EXPECT_TRUE(MatchRegexAtHead("a?b", "ab")); -} - -TEST(MatchRegexAtHeadTest, - WorksWhenRegexStartsWithRepetionOfEscapeSequence) { - EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc")); - EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b")); - - EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab")); - EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b")); - EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b")); - EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b")); -} - -TEST(MatchRegexAtHeadTest, MatchesSequentially) { - EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc")); - - EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc")); -} - -TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) { - EXPECT_FALSE(MatchRegexAnywhere("", NULL)); -} - -TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) { - EXPECT_FALSE(MatchRegexAnywhere("^a", "ba")); - EXPECT_FALSE(MatchRegexAnywhere("^$", "a")); - - EXPECT_TRUE(MatchRegexAnywhere("^a", "ab")); - EXPECT_TRUE(MatchRegexAnywhere("^", "ab")); - EXPECT_TRUE(MatchRegexAnywhere("^$", "")); -} - -TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) { - EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123")); - EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888")); -} - -TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) { - EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5")); - EXPECT_TRUE(MatchRegexAnywhere(".*=", "=")); - EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc")); -} - -TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) { - EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5")); - EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...=")); -} - -// Tests RE's implicit constructors. -TEST(RETest, ImplicitConstructorWorks) { - const RE empty(""); - EXPECT_STREQ("", empty.pattern()); - - const RE simple("hello"); - EXPECT_STREQ("hello", simple.pattern()); -} - -// Tests that RE's constructors reject invalid regular expressions. -TEST(RETest, RejectsInvalidRegex) { - EXPECT_NONFATAL_FAILURE({ - const RE normal(NULL); - }, "NULL is not a valid simple regular expression"); - - EXPECT_NONFATAL_FAILURE({ - const RE normal(".*(\\w+"); - }, "'(' is unsupported"); - - EXPECT_NONFATAL_FAILURE({ - const RE invalid("^?"); - }, "'?' can only follow a repeatable token"); -} - -// Tests RE::FullMatch(). -TEST(RETest, FullMatchWorks) { - const RE empty(""); - EXPECT_TRUE(RE::FullMatch("", empty)); - EXPECT_FALSE(RE::FullMatch("a", empty)); - - const RE re1("a"); - EXPECT_TRUE(RE::FullMatch("a", re1)); - - const RE re("a.*z"); - EXPECT_TRUE(RE::FullMatch("az", re)); - EXPECT_TRUE(RE::FullMatch("axyz", re)); - EXPECT_FALSE(RE::FullMatch("baz", re)); - EXPECT_FALSE(RE::FullMatch("azy", re)); -} - -// Tests RE::PartialMatch(). -TEST(RETest, PartialMatchWorks) { - const RE empty(""); - EXPECT_TRUE(RE::PartialMatch("", empty)); - EXPECT_TRUE(RE::PartialMatch("a", empty)); - - const RE re("a.*z"); - EXPECT_TRUE(RE::PartialMatch("az", re)); - EXPECT_TRUE(RE::PartialMatch("axyz", re)); - EXPECT_TRUE(RE::PartialMatch("baz", re)); - EXPECT_TRUE(RE::PartialMatch("azy", re)); - EXPECT_FALSE(RE::PartialMatch("zza", re)); -} - -#endif // GTEST_USES_POSIX_RE - -#if !GTEST_OS_WINDOWS_MOBILE - -TEST(CaptureTest, CapturesStdout) { - CaptureStdout(); - fprintf(stdout, "abc"); - EXPECT_STREQ("abc", GetCapturedStdout().c_str()); - - CaptureStdout(); - fprintf(stdout, "def%cghi", '\0'); - EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout())); -} - -TEST(CaptureTest, CapturesStderr) { - CaptureStderr(); - fprintf(stderr, "jkl"); - EXPECT_STREQ("jkl", GetCapturedStderr().c_str()); - - CaptureStderr(); - fprintf(stderr, "jkl%cmno", '\0'); - EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr())); -} - -// Tests that stdout and stderr capture don't interfere with each other. -TEST(CaptureTest, CapturesStdoutAndStderr) { - CaptureStdout(); - CaptureStderr(); - fprintf(stdout, "pqr"); - fprintf(stderr, "stu"); - EXPECT_STREQ("pqr", GetCapturedStdout().c_str()); - EXPECT_STREQ("stu", GetCapturedStderr().c_str()); -} - -TEST(CaptureDeathTest, CannotReenterStdoutCapture) { - CaptureStdout(); - EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(), - "Only one stdout capturer can exist at a time"); - GetCapturedStdout(); - - // We cannot test stderr capturing using death tests as they use it - // themselves. -} - -#endif // !GTEST_OS_WINDOWS_MOBILE - -TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) { - ThreadLocal t1; - EXPECT_EQ(0, t1.get()); - - ThreadLocal t2; - EXPECT_TRUE(t2.get() == NULL); -} - -TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) { - ThreadLocal t1(123); - EXPECT_EQ(123, t1.get()); - - int i = 0; - ThreadLocal t2(&i); - EXPECT_EQ(&i, t2.get()); -} - -class NoDefaultContructor { - public: - explicit NoDefaultContructor(const char*) {} - NoDefaultContructor(const NoDefaultContructor&) {} -}; - -TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) { - ThreadLocal bar(NoDefaultContructor("foo")); - bar.pointer(); -} - -TEST(ThreadLocalTest, GetAndPointerReturnSameValue) { - ThreadLocal thread_local_string; - - EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get())); - - // Verifies the condition still holds after calling set. - thread_local_string.set("foo"); - EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get())); -} - -TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) { - ThreadLocal thread_local_string; - const ThreadLocal& const_thread_local_string = - thread_local_string; - - EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer()); - - thread_local_string.set("foo"); - EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer()); -} - -#if GTEST_IS_THREADSAFE - -void AddTwo(int* param) { *param += 2; } - -TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) { - int i = 40; - ThreadWithParam thread(&AddTwo, &i, NULL); - thread.Join(); - EXPECT_EQ(42, i); -} - -TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) { - // AssertHeld() is flaky only in the presence of multiple threads accessing - // the lock. In this case, the test is robust. - EXPECT_DEATH_IF_SUPPORTED({ - Mutex m; - { MutexLock lock(&m); } - m.AssertHeld(); - }, - "thread .*hold"); -} - -TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) { - Mutex m; - MutexLock lock(&m); - m.AssertHeld(); -} - -class AtomicCounterWithMutex { - public: - explicit AtomicCounterWithMutex(Mutex* mutex) : - value_(0), mutex_(mutex), random_(42) {} - - void Increment() { - MutexLock lock(mutex_); - int temp = value_; - { - // We need to put up a memory barrier to prevent reads and writes to - // value_ rearranged with the call to SleepMilliseconds when observed - // from other threads. -#if GTEST_HAS_PTHREAD - // On POSIX, locking a mutex puts up a memory barrier. We cannot use - // Mutex and MutexLock here or rely on their memory barrier - // functionality as we are testing them here. - pthread_mutex_t memory_barrier_mutex; - GTEST_CHECK_POSIX_SUCCESS_( - pthread_mutex_init(&memory_barrier_mutex, NULL)); - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex)); - - SleepMilliseconds(random_.Generate(30)); - - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex)); - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex)); -#elif GTEST_OS_WINDOWS - // On Windows, performing an interlocked access puts up a memory barrier. - volatile LONG dummy = 0; - ::InterlockedIncrement(&dummy); - SleepMilliseconds(random_.Generate(30)); - ::InterlockedIncrement(&dummy); -#else -# error "Memory barrier not implemented on this platform." -#endif // GTEST_HAS_PTHREAD - } - value_ = temp + 1; - } - int value() const { return value_; } - - private: - volatile int value_; - Mutex* const mutex_; // Protects value_. - Random random_; -}; - -void CountingThreadFunc(pair param) { - for (int i = 0; i < param.second; ++i) - param.first->Increment(); -} - -// Tests that the mutex only lets one thread at a time to lock it. -TEST(MutexTest, OnlyOneThreadCanLockAtATime) { - Mutex mutex; - AtomicCounterWithMutex locked_counter(&mutex); - - typedef ThreadWithParam > ThreadType; - const int kCycleCount = 20; - const int kThreadCount = 7; - scoped_ptr counting_threads[kThreadCount]; - Notification threads_can_start; - // Creates and runs kThreadCount threads that increment locked_counter - // kCycleCount times each. - for (int i = 0; i < kThreadCount; ++i) { - counting_threads[i].reset(new ThreadType(&CountingThreadFunc, - make_pair(&locked_counter, - kCycleCount), - &threads_can_start)); - } - threads_can_start.Notify(); - for (int i = 0; i < kThreadCount; ++i) - counting_threads[i]->Join(); - - // If the mutex lets more than one thread to increment the counter at a - // time, they are likely to encounter a race condition and have some - // increments overwritten, resulting in the lower then expected counter - // value. - EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value()); -} - -template -void RunFromThread(void (func)(T), T param) { - ThreadWithParam thread(func, param, NULL); - thread.Join(); -} - -void RetrieveThreadLocalValue( - pair*, std::string*> param) { - *param.second = param.first->get(); -} - -TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) { - ThreadLocal thread_local_string("foo"); - EXPECT_STREQ("foo", thread_local_string.get().c_str()); - - thread_local_string.set("bar"); - EXPECT_STREQ("bar", thread_local_string.get().c_str()); - - std::string result; - RunFromThread(&RetrieveThreadLocalValue, - make_pair(&thread_local_string, &result)); - EXPECT_STREQ("foo", result.c_str()); -} - -// Keeps track of whether of destructors being called on instances of -// DestructorTracker. On Windows, waits for the destructor call reports. -class DestructorCall { - public: - DestructorCall() { - invoked_ = false; -#if GTEST_OS_WINDOWS - wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL)); - GTEST_CHECK_(wait_event_.Get() != NULL); -#endif - } - - bool CheckDestroyed() const { -#if GTEST_OS_WINDOWS - if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0) - return false; -#endif - return invoked_; - } - - void ReportDestroyed() { - invoked_ = true; -#if GTEST_OS_WINDOWS - ::SetEvent(wait_event_.Get()); -#endif - } - - static std::vector& List() { return *list_; } - - static void ResetList() { - for (size_t i = 0; i < list_->size(); ++i) { - delete list_->at(i); - } - list_->clear(); - } - - private: - bool invoked_; -#if GTEST_OS_WINDOWS - AutoHandle wait_event_; -#endif - static std::vector* const list_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall); -}; - -std::vector* const DestructorCall::list_ = - new std::vector; - -// DestructorTracker keeps track of whether its instances have been -// destroyed. -class DestructorTracker { - public: - DestructorTracker() : index_(GetNewIndex()) {} - DestructorTracker(const DestructorTracker& /* rhs */) - : index_(GetNewIndex()) {} - ~DestructorTracker() { - // We never access DestructorCall::List() concurrently, so we don't need - // to protect this access with a mutex. - DestructorCall::List()[index_]->ReportDestroyed(); - } - - private: - static size_t GetNewIndex() { - DestructorCall::List().push_back(new DestructorCall); - return DestructorCall::List().size() - 1; - } - const size_t index_; - - GTEST_DISALLOW_ASSIGN_(DestructorTracker); -}; - -typedef ThreadLocal* ThreadParam; - -void CallThreadLocalGet(ThreadParam thread_local_param) { - thread_local_param->get(); -} - -// Tests that when a ThreadLocal object dies in a thread, it destroys -// the managed object for that thread. -TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) { - DestructorCall::ResetList(); - - { - ThreadLocal thread_local_tracker; - ASSERT_EQ(0U, DestructorCall::List().size()); - - // This creates another DestructorTracker object for the main thread. - thread_local_tracker.get(); - ASSERT_EQ(1U, DestructorCall::List().size()); - ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed()); - } - - // Now thread_local_tracker has died. - ASSERT_EQ(1U, DestructorCall::List().size()); - EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); - - DestructorCall::ResetList(); -} - -// Tests that when a thread exits, the thread-local object for that -// thread is destroyed. -TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) { - DestructorCall::ResetList(); - - { - ThreadLocal thread_local_tracker; - ASSERT_EQ(0U, DestructorCall::List().size()); - - // This creates another DestructorTracker object in the new thread. - ThreadWithParam thread( - &CallThreadLocalGet, &thread_local_tracker, NULL); - thread.Join(); - - // The thread has exited, and we should have a DestroyedTracker - // instance created for it. But it may not have been destroyed yet. - ASSERT_EQ(1U, DestructorCall::List().size()); - } - - // The thread has exited and thread_local_tracker has died. - ASSERT_EQ(1U, DestructorCall::List().size()); - EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); - - DestructorCall::ResetList(); -} - -TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) { - ThreadLocal thread_local_string; - thread_local_string.set("Foo"); - EXPECT_STREQ("Foo", thread_local_string.get().c_str()); - - std::string result; - RunFromThread(&RetrieveThreadLocalValue, - make_pair(&thread_local_string, &result)); - EXPECT_TRUE(result.empty()); -} - -#endif // GTEST_IS_THREADSAFE - -#if GTEST_OS_WINDOWS -TEST(WindowsTypesTest, HANDLEIsVoidStar) { - StaticAssertTypeEq(); -} - -#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) -TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) { - StaticAssertTypeEq(); -} -#else -TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) { - StaticAssertTypeEq(); -} -#endif - -#endif // GTEST_OS_WINDOWS - -} // namespace internal -} // namespace testing diff --git a/googletest/test/gtest-printers_test.cc b/googletest/test/gtest-printers_test.cc deleted file mode 100644 index 49b3bd4..0000000 --- a/googletest/test/gtest-printers_test.cc +++ /dev/null @@ -1,1737 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) - -// Google Test - The Google C++ Testing and Mocking Framework -// -// This file tests the universal value printer. - -#include "gtest/gtest-printers.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "gtest/gtest.h" - -#if GTEST_HAS_UNORDERED_MAP_ -# include // NOLINT -#endif // GTEST_HAS_UNORDERED_MAP_ - -#if GTEST_HAS_UNORDERED_SET_ -# include // NOLINT -#endif // GTEST_HAS_UNORDERED_SET_ - -#if GTEST_HAS_STD_FORWARD_LIST_ -# include // NOLINT -#endif // GTEST_HAS_STD_FORWARD_LIST_ - -// Some user-defined types for testing the universal value printer. - -// An anonymous enum type. -enum AnonymousEnum { - kAE1 = -1, - kAE2 = 1 -}; - -// An enum without a user-defined printer. -enum EnumWithoutPrinter { - kEWP1 = -2, - kEWP2 = 42 -}; - -// An enum with a << operator. -enum EnumWithStreaming { - kEWS1 = 10 -}; - -std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) { - return os << (e == kEWS1 ? "kEWS1" : "invalid"); -} - -// An enum with a PrintTo() function. -enum EnumWithPrintTo { - kEWPT1 = 1 -}; - -void PrintTo(EnumWithPrintTo e, std::ostream* os) { - *os << (e == kEWPT1 ? "kEWPT1" : "invalid"); -} - -// A class implicitly convertible to BiggestInt. -class BiggestIntConvertible { - public: - operator ::testing::internal::BiggestInt() const { return 42; } -}; - -// A user-defined unprintable class template in the global namespace. -template -class UnprintableTemplateInGlobal { - public: - UnprintableTemplateInGlobal() : value_() {} - private: - T value_; -}; - -// A user-defined streamable type in the global namespace. -class StreamableInGlobal { - public: - virtual ~StreamableInGlobal() {} -}; - -inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) { - os << "StreamableInGlobal"; -} - -void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) { - os << "StreamableInGlobal*"; -} - -namespace foo { - -// A user-defined unprintable type in a user namespace. -class UnprintableInFoo { - public: - UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); } - double z() const { return z_; } - private: - char xy_[8]; - double z_; -}; - -// A user-defined printable type in a user-chosen namespace. -struct PrintableViaPrintTo { - PrintableViaPrintTo() : value() {} - int value; -}; - -void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) { - *os << "PrintableViaPrintTo: " << x.value; -} - -// A type with a user-defined << for printing its pointer. -struct PointerPrintable { -}; - -::std::ostream& operator<<(::std::ostream& os, - const PointerPrintable* /* x */) { - return os << "PointerPrintable*"; -} - -// A user-defined printable class template in a user-chosen namespace. -template -class PrintableViaPrintToTemplate { - public: - explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {} - - const T& value() const { return value_; } - private: - T value_; -}; - -template -void PrintTo(const PrintableViaPrintToTemplate& x, ::std::ostream* os) { - *os << "PrintableViaPrintToTemplate: " << x.value(); -} - -// A user-defined streamable class template in a user namespace. -template -class StreamableTemplateInFoo { - public: - StreamableTemplateInFoo() : value_() {} - - const T& value() const { return value_; } - private: - T value_; -}; - -template -inline ::std::ostream& operator<<(::std::ostream& os, - const StreamableTemplateInFoo& x) { - return os << "StreamableTemplateInFoo: " << x.value(); -} - -// A user-defined streamable but recursivly-defined container type in -// a user namespace, it mimics therefore std::filesystem::path or -// boost::filesystem::path. -class PathLike { - public: - struct iterator { - typedef PathLike value_type; - }; - - PathLike() {} - - iterator begin() const { return iterator(); } - iterator end() const { return iterator(); } - - friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) { - return os << "Streamable-PathLike"; - } -}; - -} // namespace foo - -namespace testing { -namespace gtest_printers_test { - -using ::std::deque; -using ::std::list; -using ::std::make_pair; -using ::std::map; -using ::std::multimap; -using ::std::multiset; -using ::std::pair; -using ::std::set; -using ::std::vector; -using ::testing::PrintToString; -using ::testing::internal::FormatForComparisonFailureMessage; -using ::testing::internal::ImplicitCast_; -using ::testing::internal::NativeArray; -using ::testing::internal::RE; -using ::testing::internal::RelationToSourceReference; -using ::testing::internal::Strings; -using ::testing::internal::UniversalPrint; -using ::testing::internal::UniversalPrinter; -using ::testing::internal::UniversalTersePrint; -#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ -using ::testing::internal::UniversalTersePrintTupleFieldsToStrings; -#endif - -// Prints a value to a string using the universal value printer. This -// is a helper for testing UniversalPrinter::Print() for various types. -template -std::string Print(const T& value) { - ::std::stringstream ss; - UniversalPrinter::Print(value, &ss); - return ss.str(); -} - -// Prints a value passed by reference to a string, using the universal -// value printer. This is a helper for testing -// UniversalPrinter::Print() for various types. -template -std::string PrintByRef(const T& value) { - ::std::stringstream ss; - UniversalPrinter::Print(value, &ss); - return ss.str(); -} - -// Tests printing various enum types. - -TEST(PrintEnumTest, AnonymousEnum) { - EXPECT_EQ("-1", Print(kAE1)); - EXPECT_EQ("1", Print(kAE2)); -} - -TEST(PrintEnumTest, EnumWithoutPrinter) { - EXPECT_EQ("-2", Print(kEWP1)); - EXPECT_EQ("42", Print(kEWP2)); -} - -TEST(PrintEnumTest, EnumWithStreaming) { - EXPECT_EQ("kEWS1", Print(kEWS1)); - EXPECT_EQ("invalid", Print(static_cast(0))); -} - -TEST(PrintEnumTest, EnumWithPrintTo) { - EXPECT_EQ("kEWPT1", Print(kEWPT1)); - EXPECT_EQ("invalid", Print(static_cast(0))); -} - -// Tests printing a class implicitly convertible to BiggestInt. - -TEST(PrintClassTest, BiggestIntConvertible) { - EXPECT_EQ("42", Print(BiggestIntConvertible())); -} - -// Tests printing various char types. - -// char. -TEST(PrintCharTest, PlainChar) { - EXPECT_EQ("'\\0'", Print('\0')); - EXPECT_EQ("'\\'' (39, 0x27)", Print('\'')); - EXPECT_EQ("'\"' (34, 0x22)", Print('"')); - EXPECT_EQ("'?' (63, 0x3F)", Print('?')); - EXPECT_EQ("'\\\\' (92, 0x5C)", Print('\\')); - EXPECT_EQ("'\\a' (7)", Print('\a')); - EXPECT_EQ("'\\b' (8)", Print('\b')); - EXPECT_EQ("'\\f' (12, 0xC)", Print('\f')); - EXPECT_EQ("'\\n' (10, 0xA)", Print('\n')); - EXPECT_EQ("'\\r' (13, 0xD)", Print('\r')); - EXPECT_EQ("'\\t' (9)", Print('\t')); - EXPECT_EQ("'\\v' (11, 0xB)", Print('\v')); - EXPECT_EQ("'\\x7F' (127)", Print('\x7F')); - EXPECT_EQ("'\\xFF' (255)", Print('\xFF')); - EXPECT_EQ("' ' (32, 0x20)", Print(' ')); - EXPECT_EQ("'a' (97, 0x61)", Print('a')); -} - -// signed char. -TEST(PrintCharTest, SignedChar) { - EXPECT_EQ("'\\0'", Print(static_cast('\0'))); - EXPECT_EQ("'\\xCE' (-50)", - Print(static_cast(-50))); -} - -// unsigned char. -TEST(PrintCharTest, UnsignedChar) { - EXPECT_EQ("'\\0'", Print(static_cast('\0'))); - EXPECT_EQ("'b' (98, 0x62)", - Print(static_cast('b'))); -} - -// Tests printing other simple, built-in types. - -// bool. -TEST(PrintBuiltInTypeTest, Bool) { - EXPECT_EQ("false", Print(false)); - EXPECT_EQ("true", Print(true)); -} - -// wchar_t. -TEST(PrintBuiltInTypeTest, Wchar_t) { - EXPECT_EQ("L'\\0'", Print(L'\0')); - EXPECT_EQ("L'\\'' (39, 0x27)", Print(L'\'')); - EXPECT_EQ("L'\"' (34, 0x22)", Print(L'"')); - EXPECT_EQ("L'?' (63, 0x3F)", Print(L'?')); - EXPECT_EQ("L'\\\\' (92, 0x5C)", Print(L'\\')); - EXPECT_EQ("L'\\a' (7)", Print(L'\a')); - EXPECT_EQ("L'\\b' (8)", Print(L'\b')); - EXPECT_EQ("L'\\f' (12, 0xC)", Print(L'\f')); - EXPECT_EQ("L'\\n' (10, 0xA)", Print(L'\n')); - EXPECT_EQ("L'\\r' (13, 0xD)", Print(L'\r')); - EXPECT_EQ("L'\\t' (9)", Print(L'\t')); - EXPECT_EQ("L'\\v' (11, 0xB)", Print(L'\v')); - EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F')); - EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF')); - EXPECT_EQ("L' ' (32, 0x20)", Print(L' ')); - EXPECT_EQ("L'a' (97, 0x61)", Print(L'a')); - EXPECT_EQ("L'\\x576' (1398)", Print(static_cast(0x576))); - EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast(0xC74D))); -} - -// Test that Int64 provides more storage than wchar_t. -TEST(PrintTypeSizeTest, Wchar_t) { - EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64)); -} - -// Various integer types. -TEST(PrintBuiltInTypeTest, Integer) { - EXPECT_EQ("'\\xFF' (255)", Print(static_cast(255))); // uint8 - EXPECT_EQ("'\\x80' (-128)", Print(static_cast(-128))); // int8 - EXPECT_EQ("65535", Print(USHRT_MAX)); // uint16 - EXPECT_EQ("-32768", Print(SHRT_MIN)); // int16 - EXPECT_EQ("4294967295", Print(UINT_MAX)); // uint32 - EXPECT_EQ("-2147483648", Print(INT_MIN)); // int32 - EXPECT_EQ("18446744073709551615", - Print(static_cast(-1))); // uint64 - EXPECT_EQ("-9223372036854775808", - Print(static_cast(1) << 63)); // int64 -} - -// Size types. -TEST(PrintBuiltInTypeTest, Size_t) { - EXPECT_EQ("1", Print(sizeof('a'))); // size_t. -#if !GTEST_OS_WINDOWS - // Windows has no ssize_t type. - EXPECT_EQ("-2", Print(static_cast(-2))); // ssize_t. -#endif // !GTEST_OS_WINDOWS -} - -// Floating-points. -TEST(PrintBuiltInTypeTest, FloatingPoints) { - EXPECT_EQ("1.5", Print(1.5f)); // float - EXPECT_EQ("-2.5", Print(-2.5)); // double -} - -// Since ::std::stringstream::operator<<(const void *) formats the pointer -// output differently with different compilers, we have to create the expected -// output first and use it as our expectation. -static std::string PrintPointer(const void* p) { - ::std::stringstream expected_result_stream; - expected_result_stream << p; - return expected_result_stream.str(); -} - -// Tests printing C strings. - -// const char*. -TEST(PrintCStringTest, Const) { - const char* p = "World"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p)); -} - -// char*. -TEST(PrintCStringTest, NonConst) { - char p[] = "Hi"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"", - Print(static_cast(p))); -} - -// NULL C string. -TEST(PrintCStringTest, Null) { - const char* p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests that C strings are escaped properly. -TEST(PrintCStringTest, EscapesProperly) { - const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f" - "\\n\\r\\t\\v\\x7F\\xFF a\"", - Print(p)); -} - -// MSVC compiler can be configured to define whar_t as a typedef -// of unsigned short. Defining an overload for const wchar_t* in that case -// would cause pointers to unsigned shorts be printed as wide strings, -// possibly accessing more memory than intended and causing invalid -// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when -// wchar_t is implemented as a native type. -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) - -// const wchar_t*. -TEST(PrintWideCStringTest, Const) { - const wchar_t* p = L"World"; - EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p)); -} - -// wchar_t*. -TEST(PrintWideCStringTest, NonConst) { - wchar_t p[] = L"Hi"; - EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"", - Print(static_cast(p))); -} - -// NULL wide C string. -TEST(PrintWideCStringTest, Null) { - const wchar_t* p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests that wide C strings are escaped properly. -TEST(PrintWideCStringTest, EscapesProperly) { - const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r', - '\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'}; - EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f" - "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"", - Print(static_cast(s))); -} -#endif // native wchar_t - -// Tests printing pointers to other char types. - -// signed char*. -TEST(PrintCharPointerTest, SignedChar) { - signed char* p = reinterpret_cast(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// const signed char*. -TEST(PrintCharPointerTest, ConstSignedChar) { - signed char* p = reinterpret_cast(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// unsigned char*. -TEST(PrintCharPointerTest, UnsignedChar) { - unsigned char* p = reinterpret_cast(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// const unsigned char*. -TEST(PrintCharPointerTest, ConstUnsignedChar) { - const unsigned char* p = reinterpret_cast(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing pointers to simple, built-in types. - -// bool*. -TEST(PrintPointerToBuiltInTypeTest, Bool) { - bool* p = reinterpret_cast(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// void*. -TEST(PrintPointerToBuiltInTypeTest, Void) { - void* p = reinterpret_cast(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// const void*. -TEST(PrintPointerToBuiltInTypeTest, ConstVoid) { - const void* p = reinterpret_cast(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing pointers to pointers. -TEST(PrintPointerToPointerTest, IntPointerPointer) { - int** p = reinterpret_cast(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing (non-member) function pointers. - -void MyFunction(int /* n */) {} - -TEST(PrintPointerTest, NonMemberFunctionPointer) { - // We cannot directly cast &MyFunction to const void* because the - // standard disallows casting between pointers to functions and - // pointers to objects, and some compilers (e.g. GCC 3.4) enforce - // this limitation. - EXPECT_EQ( - PrintPointer(reinterpret_cast( - reinterpret_cast(&MyFunction))), - Print(&MyFunction)); - int (*p)(bool) = NULL; // NOLINT - EXPECT_EQ("NULL", Print(p)); -} - -// An assertion predicate determining whether a one string is a prefix for -// another. -template -AssertionResult HasPrefix(const StringType& str, const StringType& prefix) { - if (str.find(prefix, 0) == 0) - return AssertionSuccess(); - - const bool is_wide_string = sizeof(prefix[0]) > 1; - const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; - return AssertionFailure() - << begin_string_quote << prefix << "\" is not a prefix of " - << begin_string_quote << str << "\"\n"; -} - -// Tests printing member variable pointers. Although they are called -// pointers, they don't point to a location in the address space. -// Their representation is implementation-defined. Thus they will be -// printed as raw bytes. - -struct Foo { - public: - virtual ~Foo() {} - int MyMethod(char x) { return x + 1; } - virtual char MyVirtualMethod(int /* n */) { return 'a'; } - - int value; -}; - -TEST(PrintPointerTest, MemberVariablePointer) { - EXPECT_TRUE(HasPrefix(Print(&Foo::value), - Print(sizeof(&Foo::value)) + "-byte object ")); - int (Foo::*p) = NULL; // NOLINT - EXPECT_TRUE(HasPrefix(Print(p), - Print(sizeof(p)) + "-byte object ")); -} - -// Tests printing member function pointers. Although they are called -// pointers, they don't point to a location in the address space. -// Their representation is implementation-defined. Thus they will be -// printed as raw bytes. -TEST(PrintPointerTest, MemberFunctionPointer) { - EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod), - Print(sizeof(&Foo::MyMethod)) + "-byte object ")); - EXPECT_TRUE( - HasPrefix(Print(&Foo::MyVirtualMethod), - Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object ")); - int (Foo::*p)(char) = NULL; // NOLINT - EXPECT_TRUE(HasPrefix(Print(p), - Print(sizeof(p)) + "-byte object ")); -} - -// Tests printing C arrays. - -// The difference between this and Print() is that it ensures that the -// argument is a reference to an array. -template -std::string PrintArrayHelper(T (&a)[N]) { - return Print(a); -} - -// One-dimensional array. -TEST(PrintArrayTest, OneDimensionalArray) { - int a[5] = { 1, 2, 3, 4, 5 }; - EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a)); -} - -// Two-dimensional array. -TEST(PrintArrayTest, TwoDimensionalArray) { - int a[2][5] = { - { 1, 2, 3, 4, 5 }, - { 6, 7, 8, 9, 0 } - }; - EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a)); -} - -// Array of const elements. -TEST(PrintArrayTest, ConstArray) { - const bool a[1] = { false }; - EXPECT_EQ("{ false }", PrintArrayHelper(a)); -} - -// char array without terminating NUL. -TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) { - // Array a contains '\0' in the middle and doesn't end with '\0'. - char a[] = { 'H', '\0', 'i' }; - EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a)); -} - -// const char array with terminating NUL. -TEST(PrintArrayTest, ConstCharArrayWithTerminatingNul) { - const char a[] = "\0Hi"; - EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a)); -} - -// const wchar_t array without terminating NUL. -TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) { - // Array a contains '\0' in the middle and doesn't end with '\0'. - const wchar_t a[] = { L'H', L'\0', L'i' }; - EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a)); -} - -// wchar_t array with terminating NUL. -TEST(PrintArrayTest, WConstCharArrayWithTerminatingNul) { - const wchar_t a[] = L"\0Hi"; - EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a)); -} - -// Array of objects. -TEST(PrintArrayTest, ObjectArray) { - std::string a[3] = {"Hi", "Hello", "Ni hao"}; - EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a)); -} - -// Array with many elements. -TEST(PrintArrayTest, BigArray) { - int a[100] = { 1, 2, 3 }; - EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }", - PrintArrayHelper(a)); -} - -// Tests printing ::string and ::std::string. - -#if GTEST_HAS_GLOBAL_STRING -// ::string. -TEST(PrintStringTest, StringInGlobalNamespace) { - const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; - const ::string str(s, sizeof(s)); - EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"", - Print(str)); -} -#endif // GTEST_HAS_GLOBAL_STRING - -// ::std::string. -TEST(PrintStringTest, StringInStdNamespace) { - const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; - const ::std::string str(s, sizeof(s)); - EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"", - Print(str)); -} - -TEST(PrintStringTest, StringAmbiguousHex) { - // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of: - // '\x6', '\x6B', or '\x6BA'. - - // a hex escaping sequence following by a decimal digit - EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3"))); - // a hex escaping sequence following by a hex digit (lower-case) - EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas"))); - // a hex escaping sequence following by a hex digit (upper-case) - EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA"))); - // a hex escaping sequence following by a non-xdigit - EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!"))); -} - -// Tests printing ::wstring and ::std::wstring. - -#if GTEST_HAS_GLOBAL_WSTRING -// ::wstring. -TEST(PrintWideStringTest, StringInGlobalNamespace) { - const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; - const ::wstring str(s, sizeof(s)/sizeof(wchar_t)); - EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" - "\\xD3\\x576\\x8D3\\xC74D a\\0\"", - Print(str)); -} -#endif // GTEST_HAS_GLOBAL_WSTRING - -#if GTEST_HAS_STD_WSTRING -// ::std::wstring. -TEST(PrintWideStringTest, StringInStdNamespace) { - const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; - const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t)); - EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" - "\\xD3\\x576\\x8D3\\xC74D a\\0\"", - Print(str)); -} - -TEST(PrintWideStringTest, StringAmbiguousHex) { - // same for wide strings. - EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3"))); - EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", - Print(::std::wstring(L"mm\x6" L"bananas"))); - EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", - Print(::std::wstring(L"NOM\x6" L"BANANA"))); - EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!"))); -} -#endif // GTEST_HAS_STD_WSTRING - -// Tests printing types that support generic streaming (i.e. streaming -// to std::basic_ostream for any valid Char and -// CharTraits types). - -// Tests printing a non-template type that supports generic streaming. - -class AllowsGenericStreaming {}; - -template -std::basic_ostream& operator<<( - std::basic_ostream& os, - const AllowsGenericStreaming& /* a */) { - return os << "AllowsGenericStreaming"; -} - -TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) { - AllowsGenericStreaming a; - EXPECT_EQ("AllowsGenericStreaming", Print(a)); -} - -// Tests printing a template type that supports generic streaming. - -template -class AllowsGenericStreamingTemplate {}; - -template -std::basic_ostream& operator<<( - std::basic_ostream& os, - const AllowsGenericStreamingTemplate& /* a */) { - return os << "AllowsGenericStreamingTemplate"; -} - -TEST(PrintTypeWithGenericStreamingTest, TemplateType) { - AllowsGenericStreamingTemplate a; - EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a)); -} - -// Tests printing a type that supports generic streaming and can be -// implicitly converted to another printable type. - -template -class AllowsGenericStreamingAndImplicitConversionTemplate { - public: - operator bool() const { return false; } -}; - -template -std::basic_ostream& operator<<( - std::basic_ostream& os, - const AllowsGenericStreamingAndImplicitConversionTemplate& /* a */) { - return os << "AllowsGenericStreamingAndImplicitConversionTemplate"; -} - -TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) { - AllowsGenericStreamingAndImplicitConversionTemplate a; - EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a)); -} - -#if GTEST_HAS_ABSL - -// Tests printing ::absl::string_view. - -TEST(PrintStringViewTest, SimpleStringView) { - const ::absl::string_view sp = "Hello"; - EXPECT_EQ("\"Hello\"", Print(sp)); -} - -TEST(PrintStringViewTest, UnprintableCharacters) { - const char str[] = "NUL (\0) and \r\t"; - const ::absl::string_view sp(str, sizeof(str) - 1); - EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp)); -} - -#endif // GTEST_HAS_ABSL - -// Tests printing STL containers. - -TEST(PrintStlContainerTest, EmptyDeque) { - deque empty; - EXPECT_EQ("{}", Print(empty)); -} - -TEST(PrintStlContainerTest, NonEmptyDeque) { - deque non_empty; - non_empty.push_back(1); - non_empty.push_back(3); - EXPECT_EQ("{ 1, 3 }", Print(non_empty)); -} - -#if GTEST_HAS_UNORDERED_MAP_ - -TEST(PrintStlContainerTest, OneElementHashMap) { - ::std::unordered_map map1; - map1[1] = 'a'; - EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1)); -} - -TEST(PrintStlContainerTest, HashMultiMap) { - ::std::unordered_multimap map1; - map1.insert(make_pair(5, true)); - map1.insert(make_pair(5, false)); - - // Elements of hash_multimap can be printed in any order. - const std::string result = Print(map1); - EXPECT_TRUE(result == "{ (5, true), (5, false) }" || - result == "{ (5, false), (5, true) }") - << " where Print(map1) returns \"" << result << "\"."; -} - -#endif // GTEST_HAS_UNORDERED_MAP_ - -#if GTEST_HAS_UNORDERED_SET_ - -TEST(PrintStlContainerTest, HashSet) { - ::std::unordered_set set1; - set1.insert(1); - EXPECT_EQ("{ 1 }", Print(set1)); -} - -TEST(PrintStlContainerTest, HashMultiSet) { - const int kSize = 5; - int a[kSize] = { 1, 1, 2, 5, 1 }; - ::std::unordered_multiset set1(a, a + kSize); - - // Elements of hash_multiset can be printed in any order. - const std::string result = Print(set1); - const std::string expected_pattern = "{ d, d, d, d, d }"; // d means a digit. - - // Verifies the result matches the expected pattern; also extracts - // the numbers in the result. - ASSERT_EQ(expected_pattern.length(), result.length()); - std::vector numbers; - for (size_t i = 0; i != result.length(); i++) { - if (expected_pattern[i] == 'd') { - ASSERT_NE(isdigit(static_cast(result[i])), 0); - numbers.push_back(result[i] - '0'); - } else { - EXPECT_EQ(expected_pattern[i], result[i]) << " where result is " - << result; - } - } - - // Makes sure the result contains the right numbers. - std::sort(numbers.begin(), numbers.end()); - std::sort(a, a + kSize); - EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); -} - -#endif // GTEST_HAS_UNORDERED_SET_ - -TEST(PrintStlContainerTest, List) { - const std::string a[] = {"hello", "world"}; - const list strings(a, a + 2); - EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings)); -} - -TEST(PrintStlContainerTest, Map) { - map map1; - map1[1] = true; - map1[5] = false; - map1[3] = true; - EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1)); -} - -TEST(PrintStlContainerTest, MultiMap) { - multimap map1; - // The make_pair template function would deduce the type as - // pair here, and since the key part in a multimap has to - // be constant, without a templated ctor in the pair class (as in - // libCstd on Solaris), make_pair call would fail to compile as no - // implicit conversion is found. Thus explicit typename is used - // here instead. - map1.insert(pair(true, 0)); - map1.insert(pair(true, 1)); - map1.insert(pair(false, 2)); - EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1)); -} - -TEST(PrintStlContainerTest, Set) { - const unsigned int a[] = { 3, 0, 5 }; - set set1(a, a + 3); - EXPECT_EQ("{ 0, 3, 5 }", Print(set1)); -} - -TEST(PrintStlContainerTest, MultiSet) { - const int a[] = { 1, 1, 2, 5, 1 }; - multiset set1(a, a + 5); - EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1)); -} - -#if GTEST_HAS_STD_FORWARD_LIST_ -// is available on Linux in the google3 mode, but not on -// Windows or Mac OS X. - -TEST(PrintStlContainerTest, SinglyLinkedList) { - int a[] = { 9, 2, 8 }; - const std::forward_list ints(a, a + 3); - EXPECT_EQ("{ 9, 2, 8 }", Print(ints)); -} -#endif // GTEST_HAS_STD_FORWARD_LIST_ - -TEST(PrintStlContainerTest, Pair) { - pair p(true, 5); - EXPECT_EQ("(true, 5)", Print(p)); -} - -TEST(PrintStlContainerTest, Vector) { - vector v; - v.push_back(1); - v.push_back(2); - EXPECT_EQ("{ 1, 2 }", Print(v)); -} - -TEST(PrintStlContainerTest, LongSequence) { - const int a[100] = { 1, 2, 3 }; - const vector v(a, a + 100); - EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " - "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v)); -} - -TEST(PrintStlContainerTest, NestedContainer) { - const int a1[] = { 1, 2 }; - const int a2[] = { 3, 4, 5 }; - const list l1(a1, a1 + 2); - const list l2(a2, a2 + 3); - - vector > v; - v.push_back(l1); - v.push_back(l2); - EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v)); -} - -TEST(PrintStlContainerTest, OneDimensionalNativeArray) { - const int a[3] = { 1, 2, 3 }; - NativeArray b(a, 3, RelationToSourceReference()); - EXPECT_EQ("{ 1, 2, 3 }", Print(b)); -} - -TEST(PrintStlContainerTest, TwoDimensionalNativeArray) { - const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; - NativeArray b(a, 2, RelationToSourceReference()); - EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b)); -} - -// Tests that a class named iterator isn't treated as a container. - -struct iterator { - char x; -}; - -TEST(PrintStlContainerTest, Iterator) { - iterator it = {}; - EXPECT_EQ("1-byte object <00>", Print(it)); -} - -// Tests that a class named const_iterator isn't treated as a container. - -struct const_iterator { - char x; -}; - -TEST(PrintStlContainerTest, ConstIterator) { - const_iterator it = {}; - EXPECT_EQ("1-byte object <00>", Print(it)); -} - -#if GTEST_HAS_TR1_TUPLE -// Tests printing ::std::tr1::tuples. - -// Tuples of various arities. -TEST(PrintTr1TupleTest, VariousSizes) { - ::std::tr1::tuple<> t0; - EXPECT_EQ("()", Print(t0)); - - ::std::tr1::tuple t1(5); - EXPECT_EQ("(5)", Print(t1)); - - ::std::tr1::tuple t2('a', true); - EXPECT_EQ("('a' (97, 0x61), true)", Print(t2)); - - ::std::tr1::tuple t3(false, 2, 3); - EXPECT_EQ("(false, 2, 3)", Print(t3)); - - ::std::tr1::tuple t4(false, 2, 3, 4); - EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); - - ::std::tr1::tuple t5(false, 2, 3, 4, true); - EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5)); - - ::std::tr1::tuple t6(false, 2, 3, 4, true, 6); - EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6)); - - ::std::tr1::tuple t7( - false, 2, 3, 4, true, 6, 7); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7)); - - ::std::tr1::tuple t8( - false, 2, 3, 4, true, 6, 7, true); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8)); - - ::std::tr1::tuple t9( - false, 2, 3, 4, true, 6, 7, true, 9); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9)); - - const char* const str = "8"; - // VC++ 2010's implementation of tuple of C++0x is deficient, requiring - // an explicit type cast of NULL to be used. - ::std::tr1::tuple - t10(false, 'a', static_cast(3), 4, 5, 1.5F, -2.5, str, // NOLINT - ImplicitCast_(NULL), "10"); - EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + - " pointing to \"8\", NULL, \"10\")", - Print(t10)); -} - -// Nested tuples. -TEST(PrintTr1TupleTest, NestedTuple) { - ::std::tr1::tuple< ::std::tr1::tuple, char> nested( - ::std::tr1::make_tuple(5, true), 'a'); - EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); -} - -#endif // GTEST_HAS_TR1_TUPLE - -#if GTEST_HAS_STD_TUPLE_ -// Tests printing ::std::tuples. - -// Tuples of various arities. -TEST(PrintStdTupleTest, VariousSizes) { - ::std::tuple<> t0; - EXPECT_EQ("()", Print(t0)); - - ::std::tuple t1(5); - EXPECT_EQ("(5)", Print(t1)); - - ::std::tuple t2('a', true); - EXPECT_EQ("('a' (97, 0x61), true)", Print(t2)); - - ::std::tuple t3(false, 2, 3); - EXPECT_EQ("(false, 2, 3)", Print(t3)); - - ::std::tuple t4(false, 2, 3, 4); - EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); - - ::std::tuple t5(false, 2, 3, 4, true); - EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5)); - - ::std::tuple t6(false, 2, 3, 4, true, 6); - EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6)); - - ::std::tuple t7( - false, 2, 3, 4, true, 6, 7); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7)); - - ::std::tuple t8( - false, 2, 3, 4, true, 6, 7, true); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8)); - - ::std::tuple t9( - false, 2, 3, 4, true, 6, 7, true, 9); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9)); - - const char* const str = "8"; - // VC++ 2010's implementation of tuple of C++0x is deficient, requiring - // an explicit type cast of NULL to be used. - ::std::tuple - t10(false, 'a', static_cast(3), 4, 5, 1.5F, -2.5, str, // NOLINT - ImplicitCast_(NULL), "10"); - EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + - " pointing to \"8\", NULL, \"10\")", - Print(t10)); -} - -// Nested tuples. -TEST(PrintStdTupleTest, NestedTuple) { - ::std::tuple< ::std::tuple, char> nested( - ::std::make_tuple(5, true), 'a'); - EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); -} - -#endif // GTEST_LANG_CXX11 - -#if GTEST_LANG_CXX11 -TEST(PrintNullptrT, Basic) { - EXPECT_EQ("(nullptr)", Print(nullptr)); -} -#endif // GTEST_LANG_CXX11 - -// Tests printing user-defined unprintable types. - -// Unprintable types in the global namespace. -TEST(PrintUnprintableTypeTest, InGlobalNamespace) { - EXPECT_EQ("1-byte object <00>", - Print(UnprintableTemplateInGlobal())); -} - -// Unprintable types in a user namespace. -TEST(PrintUnprintableTypeTest, InUserNamespace) { - EXPECT_EQ("16-byte object ", - Print(::foo::UnprintableInFoo())); -} - -// Unprintable types are that too big to be printed completely. - -struct Big { - Big() { memset(array, 0, sizeof(array)); } - char array[257]; -}; - -TEST(PrintUnpritableTypeTest, BigObject) { - EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 " - "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>", - Print(Big())); -} - -// Tests printing user-defined streamable types. - -// Streamable types in the global namespace. -TEST(PrintStreamableTypeTest, InGlobalNamespace) { - StreamableInGlobal x; - EXPECT_EQ("StreamableInGlobal", Print(x)); - EXPECT_EQ("StreamableInGlobal*", Print(&x)); -} - -// Printable template types in a user namespace. -TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) { - EXPECT_EQ("StreamableTemplateInFoo: 0", - Print(::foo::StreamableTemplateInFoo())); -} - -// Tests printing a user-defined recursive container type that has a << -// operator. -TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) { - ::foo::PathLike x; - EXPECT_EQ("Streamable-PathLike", Print(x)); - const ::foo::PathLike cx; - EXPECT_EQ("Streamable-PathLike", Print(cx)); -} - -// Tests printing user-defined types that have a PrintTo() function. -TEST(PrintPrintableTypeTest, InUserNamespace) { - EXPECT_EQ("PrintableViaPrintTo: 0", - Print(::foo::PrintableViaPrintTo())); -} - -// Tests printing a pointer to a user-defined type that has a << -// operator for its pointer. -TEST(PrintPrintableTypeTest, PointerInUserNamespace) { - ::foo::PointerPrintable x; - EXPECT_EQ("PointerPrintable*", Print(&x)); -} - -// Tests printing user-defined class template that have a PrintTo() function. -TEST(PrintPrintableTypeTest, TemplateInUserNamespace) { - EXPECT_EQ("PrintableViaPrintToTemplate: 5", - Print(::foo::PrintableViaPrintToTemplate(5))); -} - -// Tests that the universal printer prints both the address and the -// value of a reference. -TEST(PrintReferenceTest, PrintsAddressAndValue) { - int n = 5; - EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n)); - - int a[2][3] = { - { 0, 1, 2 }, - { 3, 4, 5 } - }; - EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }", - PrintByRef(a)); - - const ::foo::UnprintableInFoo x; - EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object " - "", - PrintByRef(x)); -} - -// Tests that the universal printer prints a function pointer passed by -// reference. -TEST(PrintReferenceTest, HandlesFunctionPointer) { - void (*fp)(int n) = &MyFunction; - const std::string fp_pointer_string = - PrintPointer(reinterpret_cast(&fp)); - // We cannot directly cast &MyFunction to const void* because the - // standard disallows casting between pointers to functions and - // pointers to objects, and some compilers (e.g. GCC 3.4) enforce - // this limitation. - const std::string fp_string = PrintPointer(reinterpret_cast( - reinterpret_cast(fp))); - EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, - PrintByRef(fp)); -} - -// Tests that the universal printer prints a member function pointer -// passed by reference. -TEST(PrintReferenceTest, HandlesMemberFunctionPointer) { - int (Foo::*p)(char ch) = &Foo::MyMethod; - EXPECT_TRUE(HasPrefix( - PrintByRef(p), - "@" + PrintPointer(reinterpret_cast(&p)) + " " + - Print(sizeof(p)) + "-byte object ")); - - char (Foo::*p2)(int n) = &Foo::MyVirtualMethod; - EXPECT_TRUE(HasPrefix( - PrintByRef(p2), - "@" + PrintPointer(reinterpret_cast(&p2)) + " " + - Print(sizeof(p2)) + "-byte object ")); -} - -// Tests that the universal printer prints a member variable pointer -// passed by reference. -TEST(PrintReferenceTest, HandlesMemberVariablePointer) { - int (Foo::*p) = &Foo::value; // NOLINT - EXPECT_TRUE(HasPrefix( - PrintByRef(p), - "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object ")); -} - -// Tests that FormatForComparisonFailureMessage(), which is used to print -// an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion -// fails, formats the operand in the desired way. - -// scalar -TEST(FormatForComparisonFailureMessageTest, WorksForScalar) { - EXPECT_STREQ("123", - FormatForComparisonFailureMessage(123, 124).c_str()); -} - -// non-char pointer -TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) { - int n = 0; - EXPECT_EQ(PrintPointer(&n), - FormatForComparisonFailureMessage(&n, &n).c_str()); -} - -// non-char array -TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) { - // In expression 'array == x', 'array' is compared by pointer. - // Therefore we want to print an array operand as a pointer. - int n[] = { 1, 2, 3 }; - EXPECT_EQ(PrintPointer(n), - FormatForComparisonFailureMessage(n, n).c_str()); -} - -// Tests formatting a char pointer when it's compared with another pointer. -// In this case we want to print it as a raw pointer, as the comparison is by -// pointer. - -// char pointer vs pointer -TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) { - // In expression 'p == x', where 'p' and 'x' are (const or not) char - // pointers, the operands are compared by pointer. Therefore we - // want to print 'p' as a pointer instead of a C string (we don't - // even know if it's supposed to point to a valid C string). - - // const char* - const char* s = "hello"; - EXPECT_EQ(PrintPointer(s), - FormatForComparisonFailureMessage(s, s).c_str()); - - // char* - char ch = 'a'; - EXPECT_EQ(PrintPointer(&ch), - FormatForComparisonFailureMessage(&ch, &ch).c_str()); -} - -// wchar_t pointer vs pointer -TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) { - // In expression 'p == x', where 'p' and 'x' are (const or not) char - // pointers, the operands are compared by pointer. Therefore we - // want to print 'p' as a pointer instead of a wide C string (we don't - // even know if it's supposed to point to a valid wide C string). - - // const wchar_t* - const wchar_t* s = L"hello"; - EXPECT_EQ(PrintPointer(s), - FormatForComparisonFailureMessage(s, s).c_str()); - - // wchar_t* - wchar_t ch = L'a'; - EXPECT_EQ(PrintPointer(&ch), - FormatForComparisonFailureMessage(&ch, &ch).c_str()); -} - -// Tests formatting a char pointer when it's compared to a string object. -// In this case we want to print the char pointer as a C string. - -#if GTEST_HAS_GLOBAL_STRING -// char pointer vs ::string -TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsString) { - const char* s = "hello \"world"; - EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped. - FormatForComparisonFailureMessage(s, ::string()).c_str()); - - // char* - char str[] = "hi\1"; - char* p = str; - EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped. - FormatForComparisonFailureMessage(p, ::string()).c_str()); -} -#endif - -// char pointer vs std::string -TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) { - const char* s = "hello \"world"; - EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped. - FormatForComparisonFailureMessage(s, ::std::string()).c_str()); - - // char* - char str[] = "hi\1"; - char* p = str; - EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped. - FormatForComparisonFailureMessage(p, ::std::string()).c_str()); -} - -#if GTEST_HAS_GLOBAL_WSTRING -// wchar_t pointer vs ::wstring -TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsWString) { - const wchar_t* s = L"hi \"world"; - EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped. - FormatForComparisonFailureMessage(s, ::wstring()).c_str()); - - // wchar_t* - wchar_t str[] = L"hi\1"; - wchar_t* p = str; - EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped. - FormatForComparisonFailureMessage(p, ::wstring()).c_str()); -} -#endif - -#if GTEST_HAS_STD_WSTRING -// wchar_t pointer vs std::wstring -TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) { - const wchar_t* s = L"hi \"world"; - EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped. - FormatForComparisonFailureMessage(s, ::std::wstring()).c_str()); - - // wchar_t* - wchar_t str[] = L"hi\1"; - wchar_t* p = str; - EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped. - FormatForComparisonFailureMessage(p, ::std::wstring()).c_str()); -} -#endif - -// Tests formatting a char array when it's compared with a pointer or array. -// In this case we want to print the array as a row pointer, as the comparison -// is by pointer. - -// char array vs pointer -TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) { - char str[] = "hi \"world\""; - char* p = NULL; - EXPECT_EQ(PrintPointer(str), - FormatForComparisonFailureMessage(str, p).c_str()); -} - -// char array vs char array -TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) { - const char str[] = "hi \"world\""; - EXPECT_EQ(PrintPointer(str), - FormatForComparisonFailureMessage(str, str).c_str()); -} - -// wchar_t array vs pointer -TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) { - wchar_t str[] = L"hi \"world\""; - wchar_t* p = NULL; - EXPECT_EQ(PrintPointer(str), - FormatForComparisonFailureMessage(str, p).c_str()); -} - -// wchar_t array vs wchar_t array -TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) { - const wchar_t str[] = L"hi \"world\""; - EXPECT_EQ(PrintPointer(str), - FormatForComparisonFailureMessage(str, str).c_str()); -} - -// Tests formatting a char array when it's compared with a string object. -// In this case we want to print the array as a C string. - -#if GTEST_HAS_GLOBAL_STRING -// char array vs string -TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsString) { - const char str[] = "hi \"w\0rld\""; - EXPECT_STREQ("\"hi \\\"w\"", // The content should be escaped. - // Embedded NUL terminates the string. - FormatForComparisonFailureMessage(str, ::string()).c_str()); -} -#endif - -// char array vs std::string -TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) { - const char str[] = "hi \"world\""; - EXPECT_STREQ("\"hi \\\"world\\\"\"", // The content should be escaped. - FormatForComparisonFailureMessage(str, ::std::string()).c_str()); -} - -#if GTEST_HAS_GLOBAL_WSTRING -// wchar_t array vs wstring -TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWString) { - const wchar_t str[] = L"hi \"world\""; - EXPECT_STREQ("L\"hi \\\"world\\\"\"", // The content should be escaped. - FormatForComparisonFailureMessage(str, ::wstring()).c_str()); -} -#endif - -#if GTEST_HAS_STD_WSTRING -// wchar_t array vs std::wstring -TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) { - const wchar_t str[] = L"hi \"w\0rld\""; - EXPECT_STREQ( - "L\"hi \\\"w\"", // The content should be escaped. - // Embedded NUL terminates the string. - FormatForComparisonFailureMessage(str, ::std::wstring()).c_str()); -} -#endif - -// Useful for testing PrintToString(). We cannot use EXPECT_EQ() -// there as its implementation uses PrintToString(). The caller must -// ensure that 'value' has no side effect. -#define EXPECT_PRINT_TO_STRING_(value, expected_string) \ - EXPECT_TRUE(PrintToString(value) == (expected_string)) \ - << " where " #value " prints as " << (PrintToString(value)) - -TEST(PrintToStringTest, WorksForScalar) { - EXPECT_PRINT_TO_STRING_(123, "123"); -} - -TEST(PrintToStringTest, WorksForPointerToConstChar) { - const char* p = "hello"; - EXPECT_PRINT_TO_STRING_(p, "\"hello\""); -} - -TEST(PrintToStringTest, WorksForPointerToNonConstChar) { - char s[] = "hello"; - char* p = s; - EXPECT_PRINT_TO_STRING_(p, "\"hello\""); -} - -TEST(PrintToStringTest, EscapesForPointerToConstChar) { - const char* p = "hello\n"; - EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\""); -} - -TEST(PrintToStringTest, EscapesForPointerToNonConstChar) { - char s[] = "hello\1"; - char* p = s; - EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\""); -} - -TEST(PrintToStringTest, WorksForArray) { - int n[3] = { 1, 2, 3 }; - EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }"); -} - -TEST(PrintToStringTest, WorksForCharArray) { - char s[] = "hello"; - EXPECT_PRINT_TO_STRING_(s, "\"hello\""); -} - -TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) { - const char str_with_nul[] = "hello\0 world"; - EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\""); - - char mutable_str_with_nul[] = "hello\0 world"; - EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\""); -} - - TEST(PrintToStringTest, ContainsNonLatin) { - // Sanity test with valid UTF-8. Prints both in hex and as text. - std::string non_ascii_str = ::std::string("오전 4:30"); - EXPECT_PRINT_TO_STRING_(non_ascii_str, - "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n" - " As Text: \"오전 4:30\""); - non_ascii_str = ::std::string("From ä — ẑ"); - EXPECT_PRINT_TO_STRING_(non_ascii_str, - "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\"" - "\n As Text: \"From ä — ẑ\""); -} - -TEST(IsValidUTF8Test, IllFormedUTF8) { - // The following test strings are ill-formed UTF-8 and are printed - // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is - // expected to fail, thus output does not contain "As Text:". - - static const char *const kTestdata[][2] = { - // 2-byte lead byte followed by a single-byte character. - {"\xC3\x74", "\"\\xC3t\""}, - // Valid 2-byte character followed by an orphan trail byte. - {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""}, - // Lead byte without trail byte. - {"abc\xC3", "\"abc\\xC3\""}, - // 3-byte lead byte, single-byte character, orphan trail byte. - {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""}, - // Truncated 3-byte character. - {"\xE2\x80", "\"\\xE2\\x80\""}, - // Truncated 3-byte character followed by valid 2-byte char. - {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""}, - // Truncated 3-byte character followed by a single-byte character. - {"\xE2\x80\x7A", "\"\\xE2\\x80z\""}, - // 3-byte lead byte followed by valid 3-byte character. - {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""}, - // 4-byte lead byte followed by valid 3-byte character. - {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""}, - // Truncated 4-byte character. - {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""}, - // Invalid UTF-8 byte sequences embedded in other chars. - {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""}, - {"abc\xC3\x84\xE2\x80\xC3\x84xyz", - "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""}, - // Non-shortest UTF-8 byte sequences are also ill-formed. - // The classics: xC0, xC1 lead byte. - {"\xC0\x80", "\"\\xC0\\x80\""}, - {"\xC1\x81", "\"\\xC1\\x81\""}, - // Non-shortest sequences. - {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""}, - {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""}, - // Last valid code point before surrogate range, should be printed as text, - // too. - {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"퟿\""}, - // Start of surrogate lead. Surrogates are not printed as text. - {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""}, - // Last non-private surrogate lead. - {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""}, - // First private-use surrogate lead. - {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""}, - // Last private-use surrogate lead. - {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""}, - // Mid-point of surrogate trail. - {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""}, - // First valid code point after surrogate range, should be printed as text, - // too. - {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""} - }; - - for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) { - EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]); - } -} - -#undef EXPECT_PRINT_TO_STRING_ - -TEST(UniversalTersePrintTest, WorksForNonReference) { - ::std::stringstream ss; - UniversalTersePrint(123, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalTersePrintTest, WorksForReference) { - const int& n = 123; - ::std::stringstream ss; - UniversalTersePrint(n, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalTersePrintTest, WorksForCString) { - const char* s1 = "abc"; - ::std::stringstream ss1; - UniversalTersePrint(s1, &ss1); - EXPECT_EQ("\"abc\"", ss1.str()); - - char* s2 = const_cast(s1); - ::std::stringstream ss2; - UniversalTersePrint(s2, &ss2); - EXPECT_EQ("\"abc\"", ss2.str()); - - const char* s3 = NULL; - ::std::stringstream ss3; - UniversalTersePrint(s3, &ss3); - EXPECT_EQ("NULL", ss3.str()); -} - -TEST(UniversalPrintTest, WorksForNonReference) { - ::std::stringstream ss; - UniversalPrint(123, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalPrintTest, WorksForReference) { - const int& n = 123; - ::std::stringstream ss; - UniversalPrint(n, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalPrintTest, WorksForCString) { - const char* s1 = "abc"; - ::std::stringstream ss1; - UniversalPrint(s1, &ss1); - EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str())); - - char* s2 = const_cast(s1); - ::std::stringstream ss2; - UniversalPrint(s2, &ss2); - EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str())); - - const char* s3 = NULL; - ::std::stringstream ss3; - UniversalPrint(s3, &ss3); - EXPECT_EQ("NULL", ss3.str()); -} - -TEST(UniversalPrintTest, WorksForCharArray) { - const char str[] = "\"Line\0 1\"\nLine 2"; - ::std::stringstream ss1; - UniversalPrint(str, &ss1); - EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str()); - - const char mutable_str[] = "\"Line\0 1\"\nLine 2"; - ::std::stringstream ss2; - UniversalPrint(mutable_str, &ss2); - EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str()); -} - -#if GTEST_HAS_TR1_TUPLE - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsEmptyTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tr1::make_tuple()); - EXPECT_EQ(0u, result.size()); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsOneTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tr1::make_tuple(1)); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ("1", result[0]); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTwoTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tr1::make_tuple(1, 'a')); - ASSERT_EQ(2u, result.size()); - EXPECT_EQ("1", result[0]); - EXPECT_EQ("'a' (97, 0x61)", result[1]); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTersely) { - const int n = 1; - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tr1::tuple(n, "a")); - ASSERT_EQ(2u, result.size()); - EXPECT_EQ("1", result[0]); - EXPECT_EQ("\"a\"", result[1]); -} - -#endif // GTEST_HAS_TR1_TUPLE - -#if GTEST_HAS_STD_TUPLE_ - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple()); - EXPECT_EQ(0u, result.size()); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::make_tuple(1)); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ("1", result[0]); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::make_tuple(1, 'a')); - ASSERT_EQ(2u, result.size()); - EXPECT_EQ("1", result[0]); - EXPECT_EQ("'a' (97, 0x61)", result[1]); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) { - const int n = 1; - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tuple(n, "a")); - ASSERT_EQ(2u, result.size()); - EXPECT_EQ("1", result[0]); - EXPECT_EQ("\"a\"", result[1]); -} - -#endif // GTEST_HAS_STD_TUPLE_ - -#if GTEST_HAS_ABSL - -TEST(PrintOptionalTest, Basic) { - absl::optional value; - EXPECT_EQ("(nullopt)", PrintToString(value)); - value = {7}; - EXPECT_EQ("(7)", PrintToString(value)); - EXPECT_EQ("(1.1)", PrintToString(absl::optional{1.1})); - EXPECT_EQ("(\"A\")", PrintToString(absl::optional{"A"})); -} -#endif // GTEST_HAS_ABSL - -} // namespace gtest_printers_test -} // namespace testing diff --git a/googletest/test/gtest-tuple_test.cc b/googletest/test/gtest-tuple_test.cc deleted file mode 100644 index bfaa3e0..0000000 --- a/googletest/test/gtest-tuple_test.cc +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) - -#include "gtest/internal/gtest-tuple.h" -#include -#include "gtest/gtest.h" - -namespace { - -using ::std::tr1::get; -using ::std::tr1::make_tuple; -using ::std::tr1::tuple; -using ::std::tr1::tuple_element; -using ::std::tr1::tuple_size; -using ::testing::StaticAssertTypeEq; - -// Tests that tuple_element >::type returns TK. -TEST(tuple_element_Test, ReturnsElementType) { - StaticAssertTypeEq >::type>(); - StaticAssertTypeEq >::type>(); - StaticAssertTypeEq >::type>(); -} - -// Tests that tuple_size::value gives the number of fields in tuple -// type T. -TEST(tuple_size_Test, ReturnsNumberOfFields) { - EXPECT_EQ(0, +tuple_size >::value); - EXPECT_EQ(1, +tuple_size >::value); - EXPECT_EQ(1, +tuple_size >::value); - EXPECT_EQ(1, +(tuple_size > >::value)); - EXPECT_EQ(2, +(tuple_size >::value)); - EXPECT_EQ(3, +(tuple_size >::value)); -} - -// Tests comparing a tuple with itself. -TEST(ComparisonTest, ComparesWithSelf) { - const tuple a(5, 'a', false); - - EXPECT_TRUE(a == a); - EXPECT_FALSE(a != a); -} - -// Tests comparing two tuples with the same value. -TEST(ComparisonTest, ComparesEqualTuples) { - const tuple a(5, true), b(5, true); - - EXPECT_TRUE(a == b); - EXPECT_FALSE(a != b); -} - -// Tests comparing two different tuples that have no reference fields. -TEST(ComparisonTest, ComparesUnequalTuplesWithoutReferenceFields) { - typedef tuple FooTuple; - - const FooTuple a(0, 'x'); - const FooTuple b(1, 'a'); - - EXPECT_TRUE(a != b); - EXPECT_FALSE(a == b); - - const FooTuple c(1, 'b'); - - EXPECT_TRUE(b != c); - EXPECT_FALSE(b == c); -} - -// Tests comparing two different tuples that have reference fields. -TEST(ComparisonTest, ComparesUnequalTuplesWithReferenceFields) { - typedef tuple FooTuple; - - int i = 5; - const char ch = 'a'; - const FooTuple a(i, ch); - - int j = 6; - const FooTuple b(j, ch); - - EXPECT_TRUE(a != b); - EXPECT_FALSE(a == b); - - j = 5; - const char ch2 = 'b'; - const FooTuple c(j, ch2); - - EXPECT_TRUE(b != c); - EXPECT_FALSE(b == c); -} - -// Tests that a tuple field with a reference type is an alias of the -// variable it's supposed to reference. -TEST(ReferenceFieldTest, IsAliasOfReferencedVariable) { - int n = 0; - tuple t(true, n); - - n = 1; - EXPECT_EQ(n, get<1>(t)) - << "Changing a underlying variable should update the reference field."; - - // Makes sure that the implementation doesn't do anything funny with - // the & operator for the return type of get<>(). - EXPECT_EQ(&n, &(get<1>(t))) - << "The address of a reference field should equal the address of " - << "the underlying variable."; - - get<1>(t) = 2; - EXPECT_EQ(2, n) - << "Changing a reference field should update the underlying variable."; -} - -// Tests that tuple's default constructor default initializes each field. -// This test needs to compile without generating warnings. -TEST(TupleConstructorTest, DefaultConstructorDefaultInitializesEachField) { - // The TR1 report requires that tuple's default constructor default - // initializes each field, even if it's a primitive type. If the - // implementation forgets to do this, this test will catch it by - // generating warnings about using uninitialized variables (assuming - // a decent compiler). - - tuple<> empty; - - tuple a1, b1; - b1 = a1; - EXPECT_EQ(0, get<0>(b1)); - - tuple a2, b2; - b2 = a2; - EXPECT_EQ(0, get<0>(b2)); - EXPECT_EQ(0.0, get<1>(b2)); - - tuple a3, b3; - b3 = a3; - EXPECT_EQ(0.0, get<0>(b3)); - EXPECT_EQ('\0', get<1>(b3)); - EXPECT_TRUE(get<2>(b3) == NULL); - - tuple a10, b10; - b10 = a10; - EXPECT_EQ(0, get<0>(b10)); - EXPECT_EQ(0, get<1>(b10)); - EXPECT_EQ(0, get<2>(b10)); - EXPECT_EQ(0, get<3>(b10)); - EXPECT_EQ(0, get<4>(b10)); - EXPECT_EQ(0, get<5>(b10)); - EXPECT_EQ(0, get<6>(b10)); - EXPECT_EQ(0, get<7>(b10)); - EXPECT_EQ(0, get<8>(b10)); - EXPECT_EQ(0, get<9>(b10)); -} - -// Tests constructing a tuple from its fields. -TEST(TupleConstructorTest, ConstructsFromFields) { - int n = 1; - // Reference field. - tuple a(n); - EXPECT_EQ(&n, &(get<0>(a))); - - // Non-reference fields. - tuple b(5, 'a'); - EXPECT_EQ(5, get<0>(b)); - EXPECT_EQ('a', get<1>(b)); - - // Const reference field. - const int m = 2; - tuple c(true, m); - EXPECT_TRUE(get<0>(c)); - EXPECT_EQ(&m, &(get<1>(c))); -} - -// Tests tuple's copy constructor. -TEST(TupleConstructorTest, CopyConstructor) { - tuple a(0.0, true); - tuple b(a); - - EXPECT_DOUBLE_EQ(0.0, get<0>(b)); - EXPECT_TRUE(get<1>(b)); -} - -// Tests constructing a tuple from another tuple that has a compatible -// but different type. -TEST(TupleConstructorTest, ConstructsFromDifferentTupleType) { - tuple a(0, 1, 'a'); - tuple b(a); - - EXPECT_DOUBLE_EQ(0.0, get<0>(b)); - EXPECT_EQ(1, get<1>(b)); - EXPECT_EQ('a', get<2>(b)); -} - -// Tests constructing a 2-tuple from an std::pair. -TEST(TupleConstructorTest, ConstructsFromPair) { - ::std::pair a(1, 'a'); - tuple b(a); - tuple c(a); -} - -// Tests assigning a tuple to another tuple with the same type. -TEST(TupleAssignmentTest, AssignsToSameTupleType) { - const tuple a(5, 7L); - tuple b; - b = a; - EXPECT_EQ(5, get<0>(b)); - EXPECT_EQ(7L, get<1>(b)); -} - -// Tests assigning a tuple to another tuple with a different but -// compatible type. -TEST(TupleAssignmentTest, AssignsToDifferentTupleType) { - const tuple a(1, 7L, true); - tuple b; - b = a; - EXPECT_EQ(1L, get<0>(b)); - EXPECT_EQ(7, get<1>(b)); - EXPECT_TRUE(get<2>(b)); -} - -// Tests assigning an std::pair to a 2-tuple. -TEST(TupleAssignmentTest, AssignsFromPair) { - const ::std::pair a(5, true); - tuple b; - b = a; - EXPECT_EQ(5, get<0>(b)); - EXPECT_TRUE(get<1>(b)); - - tuple c; - c = a; - EXPECT_EQ(5L, get<0>(c)); - EXPECT_TRUE(get<1>(c)); -} - -// A fixture for testing big tuples. -class BigTupleTest : public testing::Test { - protected: - typedef tuple BigTuple; - - BigTupleTest() : - a_(1, 0, 0, 0, 0, 0, 0, 0, 0, 2), - b_(1, 0, 0, 0, 0, 0, 0, 0, 0, 3) {} - - BigTuple a_, b_; -}; - -// Tests constructing big tuples. -TEST_F(BigTupleTest, Construction) { - BigTuple a; - BigTuple b(b_); -} - -// Tests that get(t) returns the N-th (0-based) field of tuple t. -TEST_F(BigTupleTest, get) { - EXPECT_EQ(1, get<0>(a_)); - EXPECT_EQ(2, get<9>(a_)); - - // Tests that get() works on a const tuple too. - const BigTuple a(a_); - EXPECT_EQ(1, get<0>(a)); - EXPECT_EQ(2, get<9>(a)); -} - -// Tests comparing big tuples. -TEST_F(BigTupleTest, Comparisons) { - EXPECT_TRUE(a_ == a_); - EXPECT_FALSE(a_ != a_); - - EXPECT_TRUE(a_ != b_); - EXPECT_FALSE(a_ == b_); -} - -TEST(MakeTupleTest, WorksForScalarTypes) { - tuple a; - a = make_tuple(true, 5); - EXPECT_TRUE(get<0>(a)); - EXPECT_EQ(5, get<1>(a)); - - tuple b; - b = make_tuple('a', 'b', 5); - EXPECT_EQ('a', get<0>(b)); - EXPECT_EQ('b', get<1>(b)); - EXPECT_EQ(5, get<2>(b)); -} - -TEST(MakeTupleTest, WorksForPointers) { - int a[] = { 1, 2, 3, 4 }; - const char* const str = "hi"; - int* const p = a; - - tuple t; - t = make_tuple(str, p); - EXPECT_EQ(str, get<0>(t)); - EXPECT_EQ(p, get<1>(t)); -} - -} // namespace -- cgit v0.12