1 // Copyright 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Google Test - The Google C++ Testing and Mocking Framework
32 // This file tests the universal value printer.
39 #include <forward_list>
47 #include <unordered_map>
48 #include <unordered_set>
52 #include "gtest/gtest-printers.h"
53 #include "gtest/gtest.h"
55 // Some user-defined types for testing the universal value printer.
57 // An anonymous enum type.
58 enum AnonymousEnum { kAE1 = -1, kAE2 = 1 };
60 // An enum without a user-defined printer.
61 enum EnumWithoutPrinter { kEWP1 = -2, kEWP2 = 42 };
63 // An enum with a << operator.
64 enum EnumWithStreaming { kEWS1 = 10 };
66 std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
67 return os << (e == kEWS1 ? "kEWS1" : "invalid");
70 // An enum with a PrintTo() function.
71 enum EnumWithPrintTo { kEWPT1 = 1 };
73 void PrintTo(EnumWithPrintTo e, std::ostream* os) {
74 *os << (e == kEWPT1 ? "kEWPT1" : "invalid");
77 // A class implicitly convertible to BiggestInt.
78 class BiggestIntConvertible {
80 operator ::testing::internal::BiggestInt() const { return 42; }
83 // A parent class with two child classes. The parent and one of the kids have
86 class ChildClassWithStreamOperator : public ParentClass {};
87 class ChildClassWithoutStreamOperator : public ParentClass {};
88 static void operator<<(std::ostream& os, const ParentClass&) {
91 static void operator<<(std::ostream& os, const ChildClassWithStreamOperator&) {
92 os << "ChildClassWithStreamOperator";
95 // A user-defined unprintable class template in the global namespace.
97 class UnprintableTemplateInGlobal {
99 UnprintableTemplateInGlobal() : value_() {}
105 // A user-defined streamable type in the global namespace.
106 class StreamableInGlobal {
108 virtual ~StreamableInGlobal() {}
111 inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) {
112 os << "StreamableInGlobal";
115 void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) {
116 os << "StreamableInGlobal*";
121 // A user-defined unprintable type in a user namespace.
122 class UnprintableInFoo {
124 UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
125 double z() const { return z_; }
132 // A user-defined printable type in a user-chosen namespace.
133 struct PrintableViaPrintTo {
134 PrintableViaPrintTo() : value() {}
138 void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
139 *os << "PrintableViaPrintTo: " << x.value;
142 // A type with a user-defined << for printing its pointer.
143 struct PointerPrintable {};
145 ::std::ostream& operator<<(::std::ostream& os,
146 const PointerPrintable* /* x */) {
147 return os << "PointerPrintable*";
150 // A user-defined printable class template in a user-chosen namespace.
151 template <typename T>
152 class PrintableViaPrintToTemplate {
154 explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
156 const T& value() const { return value_; }
162 template <typename T>
163 void PrintTo(const PrintableViaPrintToTemplate<T>& x, ::std::ostream* os) {
164 *os << "PrintableViaPrintToTemplate: " << x.value();
167 // A user-defined streamable class template in a user namespace.
168 template <typename T>
169 class StreamableTemplateInFoo {
171 StreamableTemplateInFoo() : value_() {}
173 const T& value() const { return value_; }
179 template <typename T>
180 inline ::std::ostream& operator<<(::std::ostream& os,
181 const StreamableTemplateInFoo<T>& x) {
182 return os << "StreamableTemplateInFoo: " << x.value();
185 // A user-defined streamable type in a user namespace whose operator<< is
186 // templated on the type of the output stream.
187 struct TemplatedStreamableInFoo {};
189 template <typename OutputStream>
190 OutputStream& operator<<(OutputStream& os,
191 const TemplatedStreamableInFoo& /*ts*/) {
192 os << "TemplatedStreamableInFoo";
196 // A user-defined streamable but recursively-defined container type in
197 // a user namespace, it mimics therefore std::filesystem::path or
198 // boost::filesystem::path.
202 typedef PathLike value_type;
204 iterator& operator++();
205 PathLike& operator*();
208 using value_type = char;
209 using const_iterator = iterator;
213 iterator begin() const { return iterator(); }
214 iterator end() const { return iterator(); }
216 friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) {
217 return os << "Streamable-PathLike";
225 template <typename T>
228 explicit Wrapper(T&& value) : value_(std::forward<T>(value)) {}
230 const T& value() const { return value_; }
239 template <typename T>
240 class UniversalPrinter<Wrapper<T>> {
242 static void Print(const Wrapper<T>& w, ::std::ostream* os) {
244 UniversalPrint(w.value(), os);
248 } // namespace internal
250 namespace gtest_printers_test {
254 using ::std::make_pair;
256 using ::std::multimap;
257 using ::std::multiset;
261 using ::testing::PrintToString;
262 using ::testing::internal::FormatForComparisonFailureMessage;
263 using ::testing::internal::ImplicitCast_;
264 using ::testing::internal::NativeArray;
265 using ::testing::internal::RelationToSourceReference;
266 using ::testing::internal::Strings;
267 using ::testing::internal::UniversalPrint;
268 using ::testing::internal::UniversalPrinter;
269 using ::testing::internal::UniversalTersePrint;
270 using ::testing::internal::UniversalTersePrintTupleFieldsToStrings;
272 // Prints a value to a string using the universal value printer. This
273 // is a helper for testing UniversalPrinter<T>::Print() for various types.
274 template <typename T>
275 std::string Print(const T& value) {
276 ::std::stringstream ss;
277 UniversalPrinter<T>::Print(value, &ss);
281 // Prints a value passed by reference to a string, using the universal
282 // value printer. This is a helper for testing
283 // UniversalPrinter<T&>::Print() for various types.
284 template <typename T>
285 std::string PrintByRef(const T& value) {
286 ::std::stringstream ss;
287 UniversalPrinter<T&>::Print(value, &ss);
291 // Tests printing various enum types.
293 TEST(PrintEnumTest, AnonymousEnum) {
294 EXPECT_EQ("-1", Print(kAE1));
295 EXPECT_EQ("1", Print(kAE2));
298 TEST(PrintEnumTest, EnumWithoutPrinter) {
299 EXPECT_EQ("-2", Print(kEWP1));
300 EXPECT_EQ("42", Print(kEWP2));
303 TEST(PrintEnumTest, EnumWithStreaming) {
304 EXPECT_EQ("kEWS1", Print(kEWS1));
305 EXPECT_EQ("invalid", Print(static_cast<EnumWithStreaming>(0)));
308 TEST(PrintEnumTest, EnumWithPrintTo) {
309 EXPECT_EQ("kEWPT1", Print(kEWPT1));
310 EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0)));
313 // Tests printing a class implicitly convertible to BiggestInt.
315 TEST(PrintClassTest, BiggestIntConvertible) {
316 EXPECT_EQ("42", Print(BiggestIntConvertible()));
319 // Tests printing various char types.
322 TEST(PrintCharTest, PlainChar) {
323 EXPECT_EQ("'\\0'", Print('\0'));
324 EXPECT_EQ("'\\'' (39, 0x27)", Print('\''));
325 EXPECT_EQ("'\"' (34, 0x22)", Print('"'));
326 EXPECT_EQ("'?' (63, 0x3F)", Print('?'));
327 EXPECT_EQ("'\\\\' (92, 0x5C)", Print('\\'));
328 EXPECT_EQ("'\\a' (7)", Print('\a'));
329 EXPECT_EQ("'\\b' (8)", Print('\b'));
330 EXPECT_EQ("'\\f' (12, 0xC)", Print('\f'));
331 EXPECT_EQ("'\\n' (10, 0xA)", Print('\n'));
332 EXPECT_EQ("'\\r' (13, 0xD)", Print('\r'));
333 EXPECT_EQ("'\\t' (9)", Print('\t'));
334 EXPECT_EQ("'\\v' (11, 0xB)", Print('\v'));
335 EXPECT_EQ("'\\x7F' (127)", Print('\x7F'));
336 EXPECT_EQ("'\\xFF' (255)", Print('\xFF'));
337 EXPECT_EQ("' ' (32, 0x20)", Print(' '));
338 EXPECT_EQ("'a' (97, 0x61)", Print('a'));
342 TEST(PrintCharTest, SignedChar) {
343 EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0')));
344 EXPECT_EQ("'\\xCE' (-50)", Print(static_cast<signed char>(-50)));
348 TEST(PrintCharTest, UnsignedChar) {
349 EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0')));
350 EXPECT_EQ("'b' (98, 0x62)", Print(static_cast<unsigned char>('b')));
353 TEST(PrintCharTest, Char16) { EXPECT_EQ("U+0041", Print(u'A')); }
355 TEST(PrintCharTest, Char32) { EXPECT_EQ("U+0041", Print(U'A')); }
358 TEST(PrintCharTest, Char8) { EXPECT_EQ("U+0041", Print(u8'A')); }
361 // Tests printing other simple, built-in types.
364 TEST(PrintBuiltInTypeTest, Bool) {
365 EXPECT_EQ("false", Print(false));
366 EXPECT_EQ("true", Print(true));
370 TEST(PrintBuiltInTypeTest, Wchar_t) {
371 EXPECT_EQ("L'\\0'", Print(L'\0'));
372 EXPECT_EQ("L'\\'' (39, 0x27)", Print(L'\''));
373 EXPECT_EQ("L'\"' (34, 0x22)", Print(L'"'));
374 EXPECT_EQ("L'?' (63, 0x3F)", Print(L'?'));
375 EXPECT_EQ("L'\\\\' (92, 0x5C)", Print(L'\\'));
376 EXPECT_EQ("L'\\a' (7)", Print(L'\a'));
377 EXPECT_EQ("L'\\b' (8)", Print(L'\b'));
378 EXPECT_EQ("L'\\f' (12, 0xC)", Print(L'\f'));
379 EXPECT_EQ("L'\\n' (10, 0xA)", Print(L'\n'));
380 EXPECT_EQ("L'\\r' (13, 0xD)", Print(L'\r'));
381 EXPECT_EQ("L'\\t' (9)", Print(L'\t'));
382 EXPECT_EQ("L'\\v' (11, 0xB)", Print(L'\v'));
383 EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F'));
384 EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF'));
385 EXPECT_EQ("L' ' (32, 0x20)", Print(L' '));
386 EXPECT_EQ("L'a' (97, 0x61)", Print(L'a'));
387 EXPECT_EQ("L'\\x576' (1398)", Print(static_cast<wchar_t>(0x576)));
388 EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast<wchar_t>(0xC74D)));
391 // Test that int64_t provides more storage than wchar_t.
392 TEST(PrintTypeSizeTest, Wchar_t) {
393 EXPECT_LT(sizeof(wchar_t), sizeof(int64_t));
396 // Various integer types.
397 TEST(PrintBuiltInTypeTest, Integer) {
398 EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255))); // uint8
399 EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128))); // int8
400 EXPECT_EQ("65535", Print(std::numeric_limits<uint16_t>::max())); // uint16
401 EXPECT_EQ("-32768", Print(std::numeric_limits<int16_t>::min())); // int16
402 EXPECT_EQ("4294967295",
403 Print(std::numeric_limits<uint32_t>::max())); // uint32
404 EXPECT_EQ("-2147483648",
405 Print(std::numeric_limits<int32_t>::min())); // int32
406 EXPECT_EQ("18446744073709551615",
407 Print(std::numeric_limits<uint64_t>::max())); // uint64
408 EXPECT_EQ("-9223372036854775808",
409 Print(std::numeric_limits<int64_t>::min())); // int64
412 Print(std::numeric_limits<char8_t>::min())); // char8_t
414 Print(std::numeric_limits<char8_t>::max())); // char8_t
417 Print(std::numeric_limits<char16_t>::min())); // char16_t
419 Print(std::numeric_limits<char16_t>::max())); // char16_t
421 Print(std::numeric_limits<char32_t>::min())); // char32_t
422 EXPECT_EQ("U+FFFFFFFF",
423 Print(std::numeric_limits<char32_t>::max())); // char32_t
427 TEST(PrintBuiltInTypeTest, Size_t) {
428 EXPECT_EQ("1", Print(sizeof('a'))); // size_t.
429 #if !GTEST_OS_WINDOWS
430 // Windows has no ssize_t type.
431 EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2))); // ssize_t.
432 #endif // !GTEST_OS_WINDOWS
435 // gcc/clang __{u,}int128_t values.
436 #if defined(__SIZEOF_INT128__)
437 TEST(PrintBuiltInTypeTest, Int128) {
439 EXPECT_EQ("0", Print(__int128_t{0}));
440 EXPECT_EQ("0", Print(__uint128_t{0}));
441 EXPECT_EQ("12345", Print(__int128_t{12345}));
442 EXPECT_EQ("12345", Print(__uint128_t{12345}));
443 EXPECT_EQ("-12345", Print(__int128_t{-12345}));
446 EXPECT_EQ("340282366920938463463374607431768211455", Print(~__uint128_t{}));
447 __int128_t max_128 = static_cast<__int128_t>(~__uint128_t{} / 2);
448 EXPECT_EQ("-170141183460469231731687303715884105728", Print(~max_128));
449 EXPECT_EQ("170141183460469231731687303715884105727", Print(max_128));
451 #endif // __SIZEOF_INT128__
454 TEST(PrintBuiltInTypeTest, FloatingPoints) {
455 EXPECT_EQ("1.5", Print(1.5f)); // float
456 EXPECT_EQ("-2.5", Print(-2.5)); // double
460 TEST(PrintBuiltInTypeTest, TypeInfo) {
462 auto res = Print(typeid(MyStruct{}));
463 // We can't guarantee that we can demangle the name, but either name should
464 // contain the substring "MyStruct".
465 EXPECT_NE(res.find("MyStruct"), res.npos) << res;
467 #endif // GTEST_HAS_RTTI
469 // Since ::std::stringstream::operator<<(const void *) formats the pointer
470 // output differently with different compilers, we have to create the expected
471 // output first and use it as our expectation.
472 static std::string PrintPointer(const void* p) {
473 ::std::stringstream expected_result_stream;
474 expected_result_stream << p;
475 return expected_result_stream.str();
478 // Tests printing C strings.
481 TEST(PrintCStringTest, Const) {
482 const char* p = "World";
483 EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p));
487 TEST(PrintCStringTest, NonConst) {
489 EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"",
490 Print(static_cast<char*>(p)));
494 TEST(PrintCStringTest, Null) {
495 const char* p = nullptr;
496 EXPECT_EQ("NULL", Print(p));
499 // Tests that C strings are escaped properly.
500 TEST(PrintCStringTest, EscapesProperly) {
501 const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
502 EXPECT_EQ(PrintPointer(p) +
503 " pointing to \"'\\\"?\\\\\\a\\b\\f"
504 "\\n\\r\\t\\v\\x7F\\xFF a\"",
510 TEST(PrintU8StringTest, Const) {
511 const char8_t* p = u8"界";
512 EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE7\\x95\\x8C\"", Print(p));
516 TEST(PrintU8StringTest, NonConst) {
518 EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE4\\xB8\\x96\"",
519 Print(static_cast<char8_t*>(p)));
523 TEST(PrintU8StringTest, Null) {
524 const char8_t* p = nullptr;
525 EXPECT_EQ("NULL", Print(p));
528 // Tests that u8 strings are escaped properly.
529 TEST(PrintU8StringTest, EscapesProperly) {
530 const char8_t* p = u8"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 世界";
531 EXPECT_EQ(PrintPointer(p) +
532 " pointing to u8\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
533 "hello \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
539 TEST(PrintU16StringTest, Const) {
540 const char16_t* p = u"界";
541 EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x754C\"", Print(p));
545 TEST(PrintU16StringTest, NonConst) {
547 EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x4E16\"",
548 Print(static_cast<char16_t*>(p)));
552 TEST(PrintU16StringTest, Null) {
553 const char16_t* p = nullptr;
554 EXPECT_EQ("NULL", Print(p));
557 // Tests that u16 strings are escaped properly.
558 TEST(PrintU16StringTest, EscapesProperly) {
559 const char16_t* p = u"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 世界";
560 EXPECT_EQ(PrintPointer(p) +
561 " pointing to u\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
562 "hello \\x4E16\\x754C\"",
567 TEST(PrintU32StringTest, Const) {
568 const char32_t* p = U"🗺️";
569 EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F5FA\\xFE0F\"", Print(p));
573 TEST(PrintU32StringTest, NonConst) {
575 EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F30C\"",
576 Print(static_cast<char32_t*>(p)));
580 TEST(PrintU32StringTest, Null) {
581 const char32_t* p = nullptr;
582 EXPECT_EQ("NULL", Print(p));
585 // Tests that u32 strings are escaped properly.
586 TEST(PrintU32StringTest, EscapesProperly) {
587 const char32_t* p = U"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 🗺️";
588 EXPECT_EQ(PrintPointer(p) +
589 " pointing to U\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
590 "hello \\x1F5FA\\xFE0F\"",
594 // MSVC compiler can be configured to define whar_t as a typedef
595 // of unsigned short. Defining an overload for const wchar_t* in that case
596 // would cause pointers to unsigned shorts be printed as wide strings,
597 // possibly accessing more memory than intended and causing invalid
598 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
599 // wchar_t is implemented as a native type.
600 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
603 TEST(PrintWideCStringTest, Const) {
604 const wchar_t* p = L"World";
605 EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p));
609 TEST(PrintWideCStringTest, NonConst) {
611 EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"",
612 Print(static_cast<wchar_t*>(p)));
615 // NULL wide C string.
616 TEST(PrintWideCStringTest, Null) {
617 const wchar_t* p = nullptr;
618 EXPECT_EQ("NULL", Print(p));
621 // Tests that wide C strings are escaped properly.
622 TEST(PrintWideCStringTest, EscapesProperly) {
623 const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b',
624 '\f', '\n', '\r', '\t', '\v', 0xD3,
625 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'};
626 EXPECT_EQ(PrintPointer(s) +
627 " pointing to L\"'\\\"?\\\\\\a\\b\\f"
628 "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
629 Print(static_cast<const wchar_t*>(s)));
631 #endif // native wchar_t
633 // Tests printing pointers to other char types.
636 TEST(PrintCharPointerTest, SignedChar) {
637 signed char* p = reinterpret_cast<signed char*>(0x1234);
638 EXPECT_EQ(PrintPointer(p), Print(p));
640 EXPECT_EQ("NULL", Print(p));
643 // const signed char*.
644 TEST(PrintCharPointerTest, ConstSignedChar) {
645 signed char* p = reinterpret_cast<signed char*>(0x1234);
646 EXPECT_EQ(PrintPointer(p), Print(p));
648 EXPECT_EQ("NULL", Print(p));
652 TEST(PrintCharPointerTest, UnsignedChar) {
653 unsigned char* p = reinterpret_cast<unsigned char*>(0x1234);
654 EXPECT_EQ(PrintPointer(p), Print(p));
656 EXPECT_EQ("NULL", Print(p));
659 // const unsigned char*.
660 TEST(PrintCharPointerTest, ConstUnsignedChar) {
661 const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234);
662 EXPECT_EQ(PrintPointer(p), Print(p));
664 EXPECT_EQ("NULL", Print(p));
667 // Tests printing pointers to simple, built-in types.
670 TEST(PrintPointerToBuiltInTypeTest, Bool) {
671 bool* p = reinterpret_cast<bool*>(0xABCD);
672 EXPECT_EQ(PrintPointer(p), Print(p));
674 EXPECT_EQ("NULL", Print(p));
678 TEST(PrintPointerToBuiltInTypeTest, Void) {
679 void* p = reinterpret_cast<void*>(0xABCD);
680 EXPECT_EQ(PrintPointer(p), Print(p));
682 EXPECT_EQ("NULL", Print(p));
686 TEST(PrintPointerToBuiltInTypeTest, ConstVoid) {
687 const void* p = reinterpret_cast<const void*>(0xABCD);
688 EXPECT_EQ(PrintPointer(p), Print(p));
690 EXPECT_EQ("NULL", Print(p));
693 // Tests printing pointers to pointers.
694 TEST(PrintPointerToPointerTest, IntPointerPointer) {
695 int** p = reinterpret_cast<int**>(0xABCD);
696 EXPECT_EQ(PrintPointer(p), Print(p));
698 EXPECT_EQ("NULL", Print(p));
701 // Tests printing (non-member) function pointers.
703 void MyFunction(int /* n */) {}
705 TEST(PrintPointerTest, NonMemberFunctionPointer) {
706 // We cannot directly cast &MyFunction to const void* because the
707 // standard disallows casting between pointers to functions and
708 // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
710 EXPECT_EQ(PrintPointer(reinterpret_cast<const void*>(
711 reinterpret_cast<internal::BiggestInt>(&MyFunction))),
713 int (*p)(bool) = NULL; // NOLINT
714 EXPECT_EQ("NULL", Print(p));
717 // An assertion predicate determining whether a one string is a prefix for
719 template <typename StringType>
720 AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
721 if (str.find(prefix, 0) == 0) return AssertionSuccess();
723 const bool is_wide_string = sizeof(prefix[0]) > 1;
724 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
725 return AssertionFailure()
726 << begin_string_quote << prefix << "\" is not a prefix of "
727 << begin_string_quote << str << "\"\n";
730 // Tests printing member variable pointers. Although they are called
731 // pointers, they don't point to a location in the address space.
732 // Their representation is implementation-defined. Thus they will be
733 // printed as raw bytes.
738 int MyMethod(char x) { return x + 1; }
739 virtual char MyVirtualMethod(int /* n */) { return 'a'; }
744 TEST(PrintPointerTest, MemberVariablePointer) {
745 EXPECT_TRUE(HasPrefix(Print(&Foo::value),
746 Print(sizeof(&Foo::value)) + "-byte object "));
747 int Foo::*p = NULL; // NOLINT
748 EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
751 // Tests printing member function pointers. Although they are called
752 // pointers, they don't point to a location in the address space.
753 // Their representation is implementation-defined. Thus they will be
754 // printed as raw bytes.
755 TEST(PrintPointerTest, MemberFunctionPointer) {
756 EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod),
757 Print(sizeof(&Foo::MyMethod)) + "-byte object "));
759 HasPrefix(Print(&Foo::MyVirtualMethod),
760 Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
761 int (Foo::*p)(char) = NULL; // NOLINT
762 EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
765 // Tests printing C arrays.
767 // The difference between this and Print() is that it ensures that the
768 // argument is a reference to an array.
769 template <typename T, size_t N>
770 std::string PrintArrayHelper(T (&a)[N]) {
774 // One-dimensional array.
775 TEST(PrintArrayTest, OneDimensionalArray) {
776 int a[5] = {1, 2, 3, 4, 5};
777 EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
780 // Two-dimensional array.
781 TEST(PrintArrayTest, TwoDimensionalArray) {
782 int a[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}};
783 EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
786 // Array of const elements.
787 TEST(PrintArrayTest, ConstArray) {
788 const bool a[1] = {false};
789 EXPECT_EQ("{ false }", PrintArrayHelper(a));
792 // char array without terminating NUL.
793 TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {
794 // Array a contains '\0' in the middle and doesn't end with '\0'.
795 char a[] = {'H', '\0', 'i'};
796 EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
799 // char array with terminating NUL.
800 TEST(PrintArrayTest, CharArrayWithTerminatingNul) {
801 const char a[] = "\0Hi";
802 EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a));
806 // char_t array without terminating NUL.
807 TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) {
808 // Array a contains '\0' in the middle and doesn't end with '\0'.
809 const char8_t a[] = {u8'H', u8'\0', u8'i'};
810 EXPECT_EQ("u8\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
813 // char8_t array with terminating NUL.
814 TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) {
815 const char8_t a[] = u8"\0世界";
816 EXPECT_EQ("u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", PrintArrayHelper(a));
820 // const char16_t array without terminating NUL.
821 TEST(PrintArrayTest, Char16ArrayWithNoTerminatingNul) {
822 // Array a contains '\0' in the middle and doesn't end with '\0'.
823 const char16_t a[] = {u'こ', u'\0', u'ん', u'に', u'ち', u'は'};
824 EXPECT_EQ("u\"\\x3053\\0\\x3093\\x306B\\x3061\\x306F\" (no terminating NUL)",
825 PrintArrayHelper(a));
828 // char16_t array with terminating NUL.
829 TEST(PrintArrayTest, Char16ArrayWithTerminatingNul) {
830 const char16_t a[] = u"\0こんにちは";
831 EXPECT_EQ("u\"\\0\\x3053\\x3093\\x306B\\x3061\\x306F\"", PrintArrayHelper(a));
834 // char32_t array without terminating NUL.
835 TEST(PrintArrayTest, Char32ArrayWithNoTerminatingNul) {
836 // Array a contains '\0' in the middle and doesn't end with '\0'.
837 const char32_t a[] = {U'👋', U'\0', U'🌌'};
838 EXPECT_EQ("U\"\\x1F44B\\0\\x1F30C\" (no terminating NUL)",
839 PrintArrayHelper(a));
842 // char32_t array with terminating NUL.
843 TEST(PrintArrayTest, Char32ArrayWithTerminatingNul) {
844 const char32_t a[] = U"\0👋🌌";
845 EXPECT_EQ("U\"\\0\\x1F44B\\x1F30C\"", PrintArrayHelper(a));
848 // wchar_t array without terminating NUL.
849 TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) {
850 // Array a contains '\0' in the middle and doesn't end with '\0'.
851 const wchar_t a[] = {L'H', L'\0', L'i'};
852 EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
855 // wchar_t array with terminating NUL.
856 TEST(PrintArrayTest, WCharArrayWithTerminatingNul) {
857 const wchar_t a[] = L"\0Hi";
858 EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a));
862 TEST(PrintArrayTest, ObjectArray) {
863 std::string a[3] = {"Hi", "Hello", "Ni hao"};
864 EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a));
867 // Array with many elements.
868 TEST(PrintArrayTest, BigArray) {
869 int a[100] = {1, 2, 3};
870 EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }",
871 PrintArrayHelper(a));
874 // Tests printing ::string and ::std::string.
877 TEST(PrintStringTest, StringInStdNamespace) {
878 const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
879 const ::std::string str(s, sizeof(s));
880 EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
884 TEST(PrintStringTest, StringAmbiguousHex) {
885 // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of:
886 // '\x6', '\x6B', or '\x6BA'.
888 // a hex escaping sequence following by a decimal digit
889 EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12"
891 // a hex escaping sequence following by a hex digit (lower-case)
892 EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6"
894 // a hex escaping sequence following by a hex digit (upper-case)
895 EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6"
897 // a hex escaping sequence following by a non-xdigit
898 EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
901 // Tests printing ::std::wstring.
902 #if GTEST_HAS_STD_WSTRING
904 TEST(PrintWideStringTest, StringInStdNamespace) {
905 const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
906 const ::std::wstring str(s, sizeof(s) / sizeof(wchar_t));
908 "L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
909 "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
913 TEST(PrintWideStringTest, StringAmbiguousHex) {
914 // same for wide strings.
915 EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12"
917 EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", Print(::std::wstring(L"mm\x6"
919 EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", Print(::std::wstring(L"NOM\x6"
921 EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
923 #endif // GTEST_HAS_STD_WSTRING
926 TEST(PrintStringTest, U8String) {
927 std::u8string str = u8"Hello, 世界";
928 EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
929 EXPECT_EQ("u8\"Hello, \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", Print(str));
933 TEST(PrintStringTest, U16String) {
934 std::u16string str = u"Hello, 世界";
935 EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
936 EXPECT_EQ("u\"Hello, \\x4E16\\x754C\"", Print(str));
939 TEST(PrintStringTest, U32String) {
940 std::u32string str = U"Hello, 🗺️";
941 EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type
942 EXPECT_EQ("U\"Hello, \\x1F5FA\\xFE0F\"", Print(str));
945 // Tests printing types that support generic streaming (i.e. streaming
946 // to std::basic_ostream<Char, CharTraits> for any valid Char and
947 // CharTraits types).
949 // Tests printing a non-template type that supports generic streaming.
951 class AllowsGenericStreaming {};
953 template <typename Char, typename CharTraits>
954 std::basic_ostream<Char, CharTraits>& operator<<(
955 std::basic_ostream<Char, CharTraits>& os,
956 const AllowsGenericStreaming& /* a */) {
957 return os << "AllowsGenericStreaming";
960 TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) {
961 AllowsGenericStreaming a;
962 EXPECT_EQ("AllowsGenericStreaming", Print(a));
965 // Tests printing a template type that supports generic streaming.
967 template <typename T>
968 class AllowsGenericStreamingTemplate {};
970 template <typename Char, typename CharTraits, typename T>
971 std::basic_ostream<Char, CharTraits>& operator<<(
972 std::basic_ostream<Char, CharTraits>& os,
973 const AllowsGenericStreamingTemplate<T>& /* a */) {
974 return os << "AllowsGenericStreamingTemplate";
977 TEST(PrintTypeWithGenericStreamingTest, TemplateType) {
978 AllowsGenericStreamingTemplate<int> a;
979 EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a));
982 // Tests printing a type that supports generic streaming and can be
983 // implicitly converted to another printable type.
985 template <typename T>
986 class AllowsGenericStreamingAndImplicitConversionTemplate {
988 operator bool() const { return false; }
991 template <typename Char, typename CharTraits, typename T>
992 std::basic_ostream<Char, CharTraits>& operator<<(
993 std::basic_ostream<Char, CharTraits>& os,
994 const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) {
995 return os << "AllowsGenericStreamingAndImplicitConversionTemplate";
998 TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
999 AllowsGenericStreamingAndImplicitConversionTemplate<int> a;
1000 EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
1003 #if GTEST_INTERNAL_HAS_STRING_VIEW
1005 // Tests printing internal::StringView.
1007 TEST(PrintStringViewTest, SimpleStringView) {
1008 const internal::StringView sp = "Hello";
1009 EXPECT_EQ("\"Hello\"", Print(sp));
1012 TEST(PrintStringViewTest, UnprintableCharacters) {
1013 const char str[] = "NUL (\0) and \r\t";
1014 const internal::StringView sp(str, sizeof(str) - 1);
1015 EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
1018 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1020 // Tests printing STL containers.
1022 TEST(PrintStlContainerTest, EmptyDeque) {
1024 EXPECT_EQ("{}", Print(empty));
1027 TEST(PrintStlContainerTest, NonEmptyDeque) {
1028 deque<int> non_empty;
1029 non_empty.push_back(1);
1030 non_empty.push_back(3);
1031 EXPECT_EQ("{ 1, 3 }", Print(non_empty));
1034 TEST(PrintStlContainerTest, OneElementHashMap) {
1035 ::std::unordered_map<int, char> map1;
1037 EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1));
1040 TEST(PrintStlContainerTest, HashMultiMap) {
1041 ::std::unordered_multimap<int, bool> map1;
1042 map1.insert(make_pair(5, true));
1043 map1.insert(make_pair(5, false));
1045 // Elements of hash_multimap can be printed in any order.
1046 const std::string result = Print(map1);
1047 EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
1048 result == "{ (5, false), (5, true) }")
1049 << " where Print(map1) returns \"" << result << "\".";
1052 TEST(PrintStlContainerTest, HashSet) {
1053 ::std::unordered_set<int> set1;
1055 EXPECT_EQ("{ 1 }", Print(set1));
1058 TEST(PrintStlContainerTest, HashMultiSet) {
1059 const int kSize = 5;
1060 int a[kSize] = {1, 1, 2, 5, 1};
1061 ::std::unordered_multiset<int> set1(a, a + kSize);
1063 // Elements of hash_multiset can be printed in any order.
1064 const std::string result = Print(set1);
1065 const std::string expected_pattern = "{ d, d, d, d, d }"; // d means a digit.
1067 // Verifies the result matches the expected pattern; also extracts
1068 // the numbers in the result.
1069 ASSERT_EQ(expected_pattern.length(), result.length());
1070 std::vector<int> numbers;
1071 for (size_t i = 0; i != result.length(); i++) {
1072 if (expected_pattern[i] == 'd') {
1073 ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
1074 numbers.push_back(result[i] - '0');
1076 EXPECT_EQ(expected_pattern[i], result[i])
1077 << " where result is " << result;
1081 // Makes sure the result contains the right numbers.
1082 std::sort(numbers.begin(), numbers.end());
1083 std::sort(a, a + kSize);
1084 EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
1087 TEST(PrintStlContainerTest, List) {
1088 const std::string a[] = {"hello", "world"};
1089 const list<std::string> strings(a, a + 2);
1090 EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings));
1093 TEST(PrintStlContainerTest, Map) {
1094 map<int, bool> map1;
1098 EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1));
1101 TEST(PrintStlContainerTest, MultiMap) {
1102 multimap<bool, int> map1;
1103 // The make_pair template function would deduce the type as
1104 // pair<bool, int> here, and since the key part in a multimap has to
1105 // be constant, without a templated ctor in the pair class (as in
1106 // libCstd on Solaris), make_pair call would fail to compile as no
1107 // implicit conversion is found. Thus explicit typename is used
1109 map1.insert(pair<const bool, int>(true, 0));
1110 map1.insert(pair<const bool, int>(true, 1));
1111 map1.insert(pair<const bool, int>(false, 2));
1112 EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1));
1115 TEST(PrintStlContainerTest, Set) {
1116 const unsigned int a[] = {3, 0, 5};
1117 set<unsigned int> set1(a, a + 3);
1118 EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
1121 TEST(PrintStlContainerTest, MultiSet) {
1122 const int a[] = {1, 1, 2, 5, 1};
1123 multiset<int> set1(a, a + 5);
1124 EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
1127 TEST(PrintStlContainerTest, SinglyLinkedList) {
1128 int a[] = {9, 2, 8};
1129 const std::forward_list<int> ints(a, a + 3);
1130 EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
1133 TEST(PrintStlContainerTest, Pair) {
1134 pair<const bool, int> p(true, 5);
1135 EXPECT_EQ("(true, 5)", Print(p));
1138 TEST(PrintStlContainerTest, Vector) {
1142 EXPECT_EQ("{ 1, 2 }", Print(v));
1145 TEST(PrintStlContainerTest, LongSequence) {
1146 const int a[100] = {1, 2, 3};
1147 const vector<int> v(a, a + 100);
1149 "{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
1150 "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }",
1154 TEST(PrintStlContainerTest, NestedContainer) {
1155 const int a1[] = {1, 2};
1156 const int a2[] = {3, 4, 5};
1157 const list<int> l1(a1, a1 + 2);
1158 const list<int> l2(a2, a2 + 3);
1160 vector<list<int>> v;
1163 EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
1166 TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
1167 const int a[3] = {1, 2, 3};
1168 NativeArray<int> b(a, 3, RelationToSourceReference());
1169 EXPECT_EQ("{ 1, 2, 3 }", Print(b));
1172 TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
1173 const int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
1174 NativeArray<int[3]> b(a, 2, RelationToSourceReference());
1175 EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
1178 // Tests that a class named iterator isn't treated as a container.
1184 TEST(PrintStlContainerTest, Iterator) {
1186 EXPECT_EQ("1-byte object <00>", Print(it));
1189 // Tests that a class named const_iterator isn't treated as a container.
1191 struct const_iterator {
1195 TEST(PrintStlContainerTest, ConstIterator) {
1196 const_iterator it = {};
1197 EXPECT_EQ("1-byte object <00>", Print(it));
1200 // Tests printing ::std::tuples.
1202 // Tuples of various arities.
1203 TEST(PrintStdTupleTest, VariousSizes) {
1205 EXPECT_EQ("()", Print(t0));
1207 ::std::tuple<int> t1(5);
1208 EXPECT_EQ("(5)", Print(t1));
1210 ::std::tuple<char, bool> t2('a', true);
1211 EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
1213 ::std::tuple<bool, int, int> t3(false, 2, 3);
1214 EXPECT_EQ("(false, 2, 3)", Print(t3));
1216 ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4);
1217 EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
1219 const char* const str = "8";
1220 ::std::tuple<bool, char, short, int32_t, int64_t, float, double, // NOLINT
1221 const char*, void*, std::string>
1222 t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT
1224 EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
1225 " pointing to \"8\", NULL, \"10\")",
1230 TEST(PrintStdTupleTest, NestedTuple) {
1231 ::std::tuple<::std::tuple<int, bool>, char> nested(::std::make_tuple(5, true),
1233 EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
1236 TEST(PrintNullptrT, Basic) { EXPECT_EQ("(nullptr)", Print(nullptr)); }
1238 TEST(PrintReferenceWrapper, Printable) {
1240 EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::ref(x)));
1241 EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::cref(x)));
1244 TEST(PrintReferenceWrapper, Unprintable) {
1245 ::foo::UnprintableInFoo up;
1247 "@" + PrintPointer(&up) +
1248 " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1249 Print(std::ref(up)));
1251 "@" + PrintPointer(&up) +
1252 " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1253 Print(std::cref(up)));
1256 // Tests printing user-defined unprintable types.
1258 // Unprintable types in the global namespace.
1259 TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
1260 EXPECT_EQ("1-byte object <00>", Print(UnprintableTemplateInGlobal<char>()));
1263 // Unprintable types in a user namespace.
1264 TEST(PrintUnprintableTypeTest, InUserNamespace) {
1265 EXPECT_EQ("16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1266 Print(::foo::UnprintableInFoo()));
1269 // Unprintable types are that too big to be printed completely.
1272 Big() { memset(array, 0, sizeof(array)); }
1276 TEST(PrintUnpritableTypeTest, BigObject) {
1278 "257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
1279 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1280 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1281 "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
1282 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1283 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1284 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
1288 // Tests printing user-defined streamable types.
1290 // Streamable types in the global namespace.
1291 TEST(PrintStreamableTypeTest, InGlobalNamespace) {
1292 StreamableInGlobal x;
1293 EXPECT_EQ("StreamableInGlobal", Print(x));
1294 EXPECT_EQ("StreamableInGlobal*", Print(&x));
1297 // Printable template types in a user namespace.
1298 TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
1299 EXPECT_EQ("StreamableTemplateInFoo: 0",
1300 Print(::foo::StreamableTemplateInFoo<int>()));
1303 TEST(PrintStreamableTypeTest, TypeInUserNamespaceWithTemplatedStreamOperator) {
1304 EXPECT_EQ("TemplatedStreamableInFoo",
1305 Print(::foo::TemplatedStreamableInFoo()));
1308 TEST(PrintStreamableTypeTest, SubclassUsesSuperclassStreamOperator) {
1310 ChildClassWithStreamOperator child_stream;
1311 ChildClassWithoutStreamOperator child_no_stream;
1312 EXPECT_EQ("ParentClass", Print(parent));
1313 EXPECT_EQ("ChildClassWithStreamOperator", Print(child_stream));
1314 EXPECT_EQ("ParentClass", Print(child_no_stream));
1317 // Tests printing a user-defined recursive container type that has a <<
1319 TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
1321 EXPECT_EQ("Streamable-PathLike", Print(x));
1322 const ::foo::PathLike cx;
1323 EXPECT_EQ("Streamable-PathLike", Print(cx));
1326 // Tests printing user-defined types that have a PrintTo() function.
1327 TEST(PrintPrintableTypeTest, InUserNamespace) {
1328 EXPECT_EQ("PrintableViaPrintTo: 0", Print(::foo::PrintableViaPrintTo()));
1331 // Tests printing a pointer to a user-defined type that has a <<
1332 // operator for its pointer.
1333 TEST(PrintPrintableTypeTest, PointerInUserNamespace) {
1334 ::foo::PointerPrintable x;
1335 EXPECT_EQ("PointerPrintable*", Print(&x));
1338 // Tests printing user-defined class template that have a PrintTo() function.
1339 TEST(PrintPrintableTypeTest, TemplateInUserNamespace) {
1340 EXPECT_EQ("PrintableViaPrintToTemplate: 5",
1341 Print(::foo::PrintableViaPrintToTemplate<int>(5)));
1344 // Tests that the universal printer prints both the address and the
1345 // value of a reference.
1346 TEST(PrintReferenceTest, PrintsAddressAndValue) {
1348 EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
1350 int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
1351 EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
1354 const ::foo::UnprintableInFoo x;
1355 EXPECT_EQ("@" + PrintPointer(&x) +
1357 "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1361 // Tests that the universal printer prints a function pointer passed by
1363 TEST(PrintReferenceTest, HandlesFunctionPointer) {
1364 void (*fp)(int n) = &MyFunction;
1365 const std::string fp_pointer_string =
1366 PrintPointer(reinterpret_cast<const void*>(&fp));
1367 // We cannot directly cast &MyFunction to const void* because the
1368 // standard disallows casting between pointers to functions and
1369 // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
1371 const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(
1372 reinterpret_cast<internal::BiggestInt>(fp)));
1373 EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, PrintByRef(fp));
1376 // Tests that the universal printer prints a member function pointer
1377 // passed by reference.
1378 TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
1379 int (Foo::*p)(char ch) = &Foo::MyMethod;
1380 EXPECT_TRUE(HasPrefix(PrintByRef(p),
1381 "@" + PrintPointer(reinterpret_cast<const void*>(&p)) +
1382 " " + Print(sizeof(p)) + "-byte object "));
1384 char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
1385 EXPECT_TRUE(HasPrefix(PrintByRef(p2),
1386 "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) +
1387 " " + Print(sizeof(p2)) + "-byte object "));
1390 // Tests that the universal printer prints a member variable pointer
1391 // passed by reference.
1392 TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
1393 int Foo::*p = &Foo::value; // NOLINT
1394 EXPECT_TRUE(HasPrefix(PrintByRef(p), "@" + PrintPointer(&p) + " " +
1395 Print(sizeof(p)) + "-byte object "));
1398 // Tests that FormatForComparisonFailureMessage(), which is used to print
1399 // an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion
1400 // fails, formats the operand in the desired way.
1403 TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
1404 EXPECT_STREQ("123", FormatForComparisonFailureMessage(123, 124).c_str());
1408 TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {
1410 EXPECT_EQ(PrintPointer(&n),
1411 FormatForComparisonFailureMessage(&n, &n).c_str());
1415 TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
1416 // In expression 'array == x', 'array' is compared by pointer.
1417 // Therefore we want to print an array operand as a pointer.
1418 int n[] = {1, 2, 3};
1419 EXPECT_EQ(PrintPointer(n), FormatForComparisonFailureMessage(n, n).c_str());
1422 // Tests formatting a char pointer when it's compared with another pointer.
1423 // In this case we want to print it as a raw pointer, as the comparison is by
1426 // char pointer vs pointer
1427 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
1428 // In expression 'p == x', where 'p' and 'x' are (const or not) char
1429 // pointers, the operands are compared by pointer. Therefore we
1430 // want to print 'p' as a pointer instead of a C string (we don't
1431 // even know if it's supposed to point to a valid C string).
1434 const char* s = "hello";
1435 EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
1439 EXPECT_EQ(PrintPointer(&ch),
1440 FormatForComparisonFailureMessage(&ch, &ch).c_str());
1443 // wchar_t pointer vs pointer
1444 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
1445 // In expression 'p == x', where 'p' and 'x' are (const or not) char
1446 // pointers, the operands are compared by pointer. Therefore we
1447 // want to print 'p' as a pointer instead of a wide C string (we don't
1448 // even know if it's supposed to point to a valid wide C string).
1451 const wchar_t* s = L"hello";
1452 EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
1456 EXPECT_EQ(PrintPointer(&ch),
1457 FormatForComparisonFailureMessage(&ch, &ch).c_str());
1460 // Tests formatting a char pointer when it's compared to a string object.
1461 // In this case we want to print the char pointer as a C string.
1463 // char pointer vs std::string
1464 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) {
1465 const char* s = "hello \"world";
1466 EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped.
1467 FormatForComparisonFailureMessage(s, ::std::string()).c_str());
1470 char str[] = "hi\1";
1472 EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped.
1473 FormatForComparisonFailureMessage(p, ::std::string()).c_str());
1476 #if GTEST_HAS_STD_WSTRING
1477 // wchar_t pointer vs std::wstring
1478 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) {
1479 const wchar_t* s = L"hi \"world";
1480 EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped.
1481 FormatForComparisonFailureMessage(s, ::std::wstring()).c_str());
1484 wchar_t str[] = L"hi\1";
1486 EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped.
1487 FormatForComparisonFailureMessage(p, ::std::wstring()).c_str());
1491 // Tests formatting a char array when it's compared with a pointer or array.
1492 // In this case we want to print the array as a row pointer, as the comparison
1495 // char array vs pointer
1496 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) {
1497 char str[] = "hi \"world\"";
1499 EXPECT_EQ(PrintPointer(str),
1500 FormatForComparisonFailureMessage(str, p).c_str());
1503 // char array vs char array
1504 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) {
1505 const char str[] = "hi \"world\"";
1506 EXPECT_EQ(PrintPointer(str),
1507 FormatForComparisonFailureMessage(str, str).c_str());
1510 // wchar_t array vs pointer
1511 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) {
1512 wchar_t str[] = L"hi \"world\"";
1513 wchar_t* p = nullptr;
1514 EXPECT_EQ(PrintPointer(str),
1515 FormatForComparisonFailureMessage(str, p).c_str());
1518 // wchar_t array vs wchar_t array
1519 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) {
1520 const wchar_t str[] = L"hi \"world\"";
1521 EXPECT_EQ(PrintPointer(str),
1522 FormatForComparisonFailureMessage(str, str).c_str());
1525 // Tests formatting a char array when it's compared with a string object.
1526 // In this case we want to print the array as a C string.
1528 // char array vs std::string
1529 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) {
1530 const char str[] = "hi \"world\"";
1531 EXPECT_STREQ("\"hi \\\"world\\\"\"", // The content should be escaped.
1532 FormatForComparisonFailureMessage(str, ::std::string()).c_str());
1535 #if GTEST_HAS_STD_WSTRING
1536 // wchar_t array vs std::wstring
1537 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
1538 const wchar_t str[] = L"hi \"w\0rld\"";
1540 "L\"hi \\\"w\"", // The content should be escaped.
1541 // Embedded NUL terminates the string.
1542 FormatForComparisonFailureMessage(str, ::std::wstring()).c_str());
1546 // Useful for testing PrintToString(). We cannot use EXPECT_EQ()
1547 // there as its implementation uses PrintToString(). The caller must
1548 // ensure that 'value' has no side effect.
1549 #define EXPECT_PRINT_TO_STRING_(value, expected_string) \
1550 EXPECT_TRUE(PrintToString(value) == (expected_string)) \
1551 << " where " #value " prints as " << (PrintToString(value))
1553 TEST(PrintToStringTest, WorksForScalar) { EXPECT_PRINT_TO_STRING_(123, "123"); }
1555 TEST(PrintToStringTest, WorksForPointerToConstChar) {
1556 const char* p = "hello";
1557 EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1560 TEST(PrintToStringTest, WorksForPointerToNonConstChar) {
1563 EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1566 TEST(PrintToStringTest, EscapesForPointerToConstChar) {
1567 const char* p = "hello\n";
1568 EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\"");
1571 TEST(PrintToStringTest, EscapesForPointerToNonConstChar) {
1572 char s[] = "hello\1";
1574 EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\"");
1577 TEST(PrintToStringTest, WorksForArray) {
1578 int n[3] = {1, 2, 3};
1579 EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }");
1582 TEST(PrintToStringTest, WorksForCharArray) {
1584 EXPECT_PRINT_TO_STRING_(s, "\"hello\"");
1587 TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {
1588 const char str_with_nul[] = "hello\0 world";
1589 EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\"");
1591 char mutable_str_with_nul[] = "hello\0 world";
1592 EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\"");
1595 TEST(PrintToStringTest, ContainsNonLatin) {
1596 // Test with valid UTF-8. Prints both in hex and as text.
1597 std::string non_ascii_str = ::std::string("오전 4:30");
1598 EXPECT_PRINT_TO_STRING_(non_ascii_str,
1599 "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n"
1600 " As Text: \"오전 4:30\"");
1601 non_ascii_str = ::std::string("From ä — ẑ");
1602 EXPECT_PRINT_TO_STRING_(non_ascii_str,
1603 "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\""
1604 "\n As Text: \"From ä — ẑ\"");
1607 TEST(IsValidUTF8Test, IllFormedUTF8) {
1608 // The following test strings are ill-formed UTF-8 and are printed
1609 // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is
1610 // expected to fail, thus output does not contain "As Text:".
1612 static const char* const kTestdata[][2] = {
1613 // 2-byte lead byte followed by a single-byte character.
1614 {"\xC3\x74", "\"\\xC3t\""},
1615 // Valid 2-byte character followed by an orphan trail byte.
1616 {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""},
1617 // Lead byte without trail byte.
1618 {"abc\xC3", "\"abc\\xC3\""},
1619 // 3-byte lead byte, single-byte character, orphan trail byte.
1620 {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""},
1621 // Truncated 3-byte character.
1622 {"\xE2\x80", "\"\\xE2\\x80\""},
1623 // Truncated 3-byte character followed by valid 2-byte char.
1624 {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""},
1625 // Truncated 3-byte character followed by a single-byte character.
1626 {"\xE2\x80\x7A", "\"\\xE2\\x80z\""},
1627 // 3-byte lead byte followed by valid 3-byte character.
1628 {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""},
1629 // 4-byte lead byte followed by valid 3-byte character.
1630 {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""},
1631 // Truncated 4-byte character.
1632 {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""},
1633 // Invalid UTF-8 byte sequences embedded in other chars.
1634 {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""},
1635 {"abc\xC3\x84\xE2\x80\xC3\x84xyz",
1636 "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""},
1637 // Non-shortest UTF-8 byte sequences are also ill-formed.
1638 // The classics: xC0, xC1 lead byte.
1639 {"\xC0\x80", "\"\\xC0\\x80\""},
1640 {"\xC1\x81", "\"\\xC1\\x81\""},
1641 // Non-shortest sequences.
1642 {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
1643 {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
1644 // Last valid code point before surrogate range, should be printed as
1647 {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"\""},
1648 // Start of surrogate lead. Surrogates are not printed as text.
1649 {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""},
1650 // Last non-private surrogate lead.
1651 {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""},
1652 // First private-use surrogate lead.
1653 {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""},
1654 // Last private-use surrogate lead.
1655 {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
1656 // Mid-point of surrogate trail.
1657 {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
1658 // First valid code point after surrogate range, should be printed as
1661 {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""}};
1663 for (int i = 0; i < int(sizeof(kTestdata) / sizeof(kTestdata[0])); ++i) {
1664 EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
1668 #undef EXPECT_PRINT_TO_STRING_
1670 TEST(UniversalTersePrintTest, WorksForNonReference) {
1671 ::std::stringstream ss;
1672 UniversalTersePrint(123, &ss);
1673 EXPECT_EQ("123", ss.str());
1676 TEST(UniversalTersePrintTest, WorksForReference) {
1678 ::std::stringstream ss;
1679 UniversalTersePrint(n, &ss);
1680 EXPECT_EQ("123", ss.str());
1683 TEST(UniversalTersePrintTest, WorksForCString) {
1684 const char* s1 = "abc";
1685 ::std::stringstream ss1;
1686 UniversalTersePrint(s1, &ss1);
1687 EXPECT_EQ("\"abc\"", ss1.str());
1689 char* s2 = const_cast<char*>(s1);
1690 ::std::stringstream ss2;
1691 UniversalTersePrint(s2, &ss2);
1692 EXPECT_EQ("\"abc\"", ss2.str());
1694 const char* s3 = nullptr;
1695 ::std::stringstream ss3;
1696 UniversalTersePrint(s3, &ss3);
1697 EXPECT_EQ("NULL", ss3.str());
1700 TEST(UniversalPrintTest, WorksForNonReference) {
1701 ::std::stringstream ss;
1702 UniversalPrint(123, &ss);
1703 EXPECT_EQ("123", ss.str());
1706 TEST(UniversalPrintTest, WorksForReference) {
1708 ::std::stringstream ss;
1709 UniversalPrint(n, &ss);
1710 EXPECT_EQ("123", ss.str());
1713 TEST(UniversalPrintTest, WorksForPairWithConst) {
1714 std::pair<const Wrapper<std::string>, int> p(Wrapper<std::string>("abc"), 1);
1715 ::std::stringstream ss;
1716 UniversalPrint(p, &ss);
1717 EXPECT_EQ("(Wrapper(\"abc\"), 1)", ss.str());
1720 TEST(UniversalPrintTest, WorksForCString) {
1721 const char* s1 = "abc";
1722 ::std::stringstream ss1;
1723 UniversalPrint(s1, &ss1);
1724 EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str()));
1726 char* s2 = const_cast<char*>(s1);
1727 ::std::stringstream ss2;
1728 UniversalPrint(s2, &ss2);
1729 EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str()));
1731 const char* s3 = nullptr;
1732 ::std::stringstream ss3;
1733 UniversalPrint(s3, &ss3);
1734 EXPECT_EQ("NULL", ss3.str());
1737 TEST(UniversalPrintTest, WorksForCharArray) {
1738 const char str[] = "\"Line\0 1\"\nLine 2";
1739 ::std::stringstream ss1;
1740 UniversalPrint(str, &ss1);
1741 EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str());
1743 const char mutable_str[] = "\"Line\0 1\"\nLine 2";
1744 ::std::stringstream ss2;
1745 UniversalPrint(mutable_str, &ss2);
1746 EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str());
1749 TEST(UniversalPrintTest, IncompleteType) {
1751 char some_object = 0;
1752 EXPECT_EQ("(incomplete type)",
1753 PrintToString(reinterpret_cast<Incomplete&>(some_object)));
1756 TEST(UniversalPrintTest, SmartPointers) {
1757 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
1758 std::unique_ptr<int> p(new int(17));
1759 EXPECT_EQ("(ptr = " + PrintPointer(p.get()) + ", value = 17)",
1761 std::unique_ptr<int[]> p2(new int[2]);
1762 EXPECT_EQ("(" + PrintPointer(p2.get()) + ")", PrintToString(p2));
1764 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
1765 std::shared_ptr<int> p3(new int(1979));
1766 EXPECT_EQ("(ptr = " + PrintPointer(p3.get()) + ", value = 1979)",
1768 #if __cpp_lib_shared_ptr_arrays >= 201611L
1769 std::shared_ptr<int[]> p4(new int[2]);
1770 EXPECT_EQ("(" + PrintPointer(p4.get()) + ")", PrintToString(p4));
1774 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
1775 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int>()));
1776 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int>()));
1777 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile const int>()));
1778 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int[]>()));
1779 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int[]>()));
1780 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int[]>()));
1781 EXPECT_EQ("(nullptr)",
1782 PrintToString(std::unique_ptr<volatile const int[]>()));
1783 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
1784 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int>()));
1785 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int>()));
1786 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile const int>()));
1787 #if __cpp_lib_shared_ptr_arrays >= 201611L
1788 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int[]>()));
1789 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int[]>()));
1790 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int[]>()));
1791 EXPECT_EQ("(nullptr)",
1792 PrintToString(std::shared_ptr<volatile const int[]>()));
1796 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<void, void (*)(void*)>(
1797 nullptr, nullptr)));
1798 EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
1800 std::unique_ptr<void, void (*)(void*)>(p.get(), [](void*) {})));
1801 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<void>()));
1802 EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
1803 PrintToString(std::shared_ptr<void>(p.get(), [](void*) {})));
1806 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
1807 Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
1808 EXPECT_EQ(0u, result.size());
1811 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
1813 UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1));
1814 ASSERT_EQ(1u, result.size());
1815 EXPECT_EQ("1", result[0]);
1818 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
1820 UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1, 'a'));
1821 ASSERT_EQ(2u, result.size());
1822 EXPECT_EQ("1", result[0]);
1823 EXPECT_EQ("'a' (97, 0x61)", result[1]);
1826 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
1828 Strings result = UniversalTersePrintTupleFieldsToStrings(
1829 ::std::tuple<const int&, const char*>(n, "a"));
1830 ASSERT_EQ(2u, result.size());
1831 EXPECT_EQ("1", result[0]);
1832 EXPECT_EQ("\"a\"", result[1]);
1835 #if GTEST_INTERNAL_HAS_ANY
1836 class PrintAnyTest : public ::testing::Test {
1838 template <typename T>
1839 static std::string ExpectedTypeName() {
1841 return internal::GetTypeName<T>();
1843 return "<unknown_type>";
1844 #endif // GTEST_HAS_RTTI
1848 TEST_F(PrintAnyTest, Empty) {
1850 EXPECT_EQ("no value", PrintToString(any));
1853 TEST_F(PrintAnyTest, NonEmpty) {
1855 constexpr int val1 = 10;
1856 const std::string val2 = "content";
1859 EXPECT_EQ("value of type " + ExpectedTypeName<int>(), PrintToString(any));
1862 EXPECT_EQ("value of type " + ExpectedTypeName<std::string>(),
1863 PrintToString(any));
1865 #endif // GTEST_INTERNAL_HAS_ANY
1867 #if GTEST_INTERNAL_HAS_OPTIONAL
1868 TEST(PrintOptionalTest, Basic) {
1869 EXPECT_EQ("(nullopt)", PrintToString(internal::Nullopt()));
1870 internal::Optional<int> value;
1871 EXPECT_EQ("(nullopt)", PrintToString(value));
1873 EXPECT_EQ("(7)", PrintToString(value));
1874 EXPECT_EQ("(1.1)", PrintToString(internal::Optional<double>{1.1}));
1875 EXPECT_EQ("(\"A\")", PrintToString(internal::Optional<std::string>{"A"}));
1877 #endif // GTEST_INTERNAL_HAS_OPTIONAL
1879 #if GTEST_INTERNAL_HAS_VARIANT
1880 struct NonPrintable {
1881 unsigned char contents = 17;
1884 TEST(PrintOneofTest, Basic) {
1885 using Type = internal::Variant<int, StreamableInGlobal, NonPrintable>;
1886 EXPECT_EQ("('int(index = 0)' with value 7)", PrintToString(Type(7)));
1887 EXPECT_EQ("('StreamableInGlobal(index = 1)' with value StreamableInGlobal)",
1888 PrintToString(Type(StreamableInGlobal{})));
1890 "('testing::gtest_printers_test::NonPrintable(index = 2)' with value "
1891 "1-byte object <11>)",
1892 PrintToString(Type(NonPrintable{})));
1894 #endif // GTEST_INTERNAL_HAS_VARIANT
1899 * This is a synthetic pointer to a fixed size string.
1903 string_ptr(const char* data, size_t size) : data_(data), size_(size) {}
1905 string_ptr& operator++() noexcept {
1910 string_ref operator*() const noexcept;
1918 * This is a synthetic reference of a fixed size string.
1922 string_ref(const char* data, size_t size) : data_(data), size_(size) {}
1924 string_ptr operator&() const noexcept { return {data_, size_}; } // NOLINT
1926 bool operator==(const char* s) const noexcept {
1927 if (size_ > 0 && data_[size_ - 1] != 0) {
1928 return std::string(data_, size_) == std::string(s);
1930 return std::string(data_) == std::string(s);
1939 string_ref string_ptr::operator*() const noexcept { return {data_, size_}; }
1941 TEST(string_ref, compare) {
1942 const char* s = "alex\0davidjohn\0";
1943 string_ptr ptr(s, 5);
1944 EXPECT_EQ(*ptr, "alex");
1945 EXPECT_TRUE(*ptr == "alex");
1947 EXPECT_EQ(*ptr, "david");
1948 EXPECT_TRUE(*ptr == "david");
1950 EXPECT_EQ(*ptr, "john");
1955 } // namespace gtest_printers_test
1956 } // namespace testing