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.
31 // Google Test - The Google C++ Testing and Mocking Framework
33 // This file tests the universal value printer.
40 #include <forward_list>
46 #include <unordered_map>
47 #include <unordered_set>
51 #include "gtest/gtest-printers.h"
52 #include "gtest/gtest.h"
54 // Some user-defined types for testing the universal value printer.
56 // An anonymous enum type.
62 // An enum without a user-defined printer.
63 enum EnumWithoutPrinter {
68 // An enum with a << operator.
69 enum EnumWithStreaming {
73 std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
74 return os << (e == kEWS1 ? "kEWS1" : "invalid");
77 // An enum with a PrintTo() function.
78 enum EnumWithPrintTo {
82 void PrintTo(EnumWithPrintTo e, std::ostream* os) {
83 *os << (e == kEWPT1 ? "kEWPT1" : "invalid");
86 // A class implicitly convertible to BiggestInt.
87 class BiggestIntConvertible {
89 operator ::testing::internal::BiggestInt() const { return 42; }
92 // A user-defined unprintable class template in the global namespace.
94 class UnprintableTemplateInGlobal {
96 UnprintableTemplateInGlobal() : value_() {}
101 // A user-defined streamable type in the global namespace.
102 class StreamableInGlobal {
104 virtual ~StreamableInGlobal() {}
107 inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) {
108 os << "StreamableInGlobal";
111 void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) {
112 os << "StreamableInGlobal*";
117 // A user-defined unprintable type in a user namespace.
118 class UnprintableInFoo {
120 UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
121 double z() const { return z_; }
127 // A user-defined printable type in a user-chosen namespace.
128 struct PrintableViaPrintTo {
129 PrintableViaPrintTo() : value() {}
133 void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
134 *os << "PrintableViaPrintTo: " << x.value;
137 // A type with a user-defined << for printing its pointer.
138 struct PointerPrintable {
141 ::std::ostream& operator<<(::std::ostream& os,
142 const PointerPrintable* /* x */) {
143 return os << "PointerPrintable*";
146 // A user-defined printable class template in a user-chosen namespace.
147 template <typename T>
148 class PrintableViaPrintToTemplate {
150 explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
152 const T& value() const { return value_; }
157 template <typename T>
158 void PrintTo(const PrintableViaPrintToTemplate<T>& x, ::std::ostream* os) {
159 *os << "PrintableViaPrintToTemplate: " << x.value();
162 // A user-defined streamable class template in a user namespace.
163 template <typename T>
164 class StreamableTemplateInFoo {
166 StreamableTemplateInFoo() : value_() {}
168 const T& value() const { return value_; }
173 template <typename T>
174 inline ::std::ostream& operator<<(::std::ostream& os,
175 const StreamableTemplateInFoo<T>& x) {
176 return os << "StreamableTemplateInFoo: " << x.value();
179 // A user-defined streamable but recursivly-defined container type in
180 // a user namespace, it mimics therefore std::filesystem::path or
181 // boost::filesystem::path.
185 typedef PathLike value_type;
187 iterator& operator++();
188 PathLike& operator*();
191 using value_type = char;
192 using const_iterator = iterator;
196 iterator begin() const { return iterator(); }
197 iterator end() const { return iterator(); }
199 friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) {
200 return os << "Streamable-PathLike";
207 namespace gtest_printers_test {
211 using ::std::make_pair;
213 using ::std::multimap;
214 using ::std::multiset;
218 using ::testing::PrintToString;
219 using ::testing::internal::FormatForComparisonFailureMessage;
220 using ::testing::internal::ImplicitCast_;
221 using ::testing::internal::NativeArray;
222 using ::testing::internal::RE;
223 using ::testing::internal::RelationToSourceReference;
224 using ::testing::internal::Strings;
225 using ::testing::internal::UniversalPrint;
226 using ::testing::internal::UniversalPrinter;
227 using ::testing::internal::UniversalTersePrint;
228 using ::testing::internal::UniversalTersePrintTupleFieldsToStrings;
230 // Prints a value to a string using the universal value printer. This
231 // is a helper for testing UniversalPrinter<T>::Print() for various types.
232 template <typename T>
233 std::string Print(const T& value) {
234 ::std::stringstream ss;
235 UniversalPrinter<T>::Print(value, &ss);
239 // Prints a value passed by reference to a string, using the universal
240 // value printer. This is a helper for testing
241 // UniversalPrinter<T&>::Print() for various types.
242 template <typename T>
243 std::string PrintByRef(const T& value) {
244 ::std::stringstream ss;
245 UniversalPrinter<T&>::Print(value, &ss);
249 // Tests printing various enum types.
251 TEST(PrintEnumTest, AnonymousEnum) {
252 EXPECT_EQ("-1", Print(kAE1));
253 EXPECT_EQ("1", Print(kAE2));
256 TEST(PrintEnumTest, EnumWithoutPrinter) {
257 EXPECT_EQ("-2", Print(kEWP1));
258 EXPECT_EQ("42", Print(kEWP2));
261 TEST(PrintEnumTest, EnumWithStreaming) {
262 EXPECT_EQ("kEWS1", Print(kEWS1));
263 EXPECT_EQ("invalid", Print(static_cast<EnumWithStreaming>(0)));
266 TEST(PrintEnumTest, EnumWithPrintTo) {
267 EXPECT_EQ("kEWPT1", Print(kEWPT1));
268 EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0)));
271 // Tests printing a class implicitly convertible to BiggestInt.
273 TEST(PrintClassTest, BiggestIntConvertible) {
274 EXPECT_EQ("42", Print(BiggestIntConvertible()));
277 // Tests printing various char types.
280 TEST(PrintCharTest, PlainChar) {
281 EXPECT_EQ("'\\0'", Print('\0'));
282 EXPECT_EQ("'\\'' (39, 0x27)", Print('\''));
283 EXPECT_EQ("'\"' (34, 0x22)", Print('"'));
284 EXPECT_EQ("'?' (63, 0x3F)", Print('?'));
285 EXPECT_EQ("'\\\\' (92, 0x5C)", Print('\\'));
286 EXPECT_EQ("'\\a' (7)", Print('\a'));
287 EXPECT_EQ("'\\b' (8)", Print('\b'));
288 EXPECT_EQ("'\\f' (12, 0xC)", Print('\f'));
289 EXPECT_EQ("'\\n' (10, 0xA)", Print('\n'));
290 EXPECT_EQ("'\\r' (13, 0xD)", Print('\r'));
291 EXPECT_EQ("'\\t' (9)", Print('\t'));
292 EXPECT_EQ("'\\v' (11, 0xB)", Print('\v'));
293 EXPECT_EQ("'\\x7F' (127)", Print('\x7F'));
294 EXPECT_EQ("'\\xFF' (255)", Print('\xFF'));
295 EXPECT_EQ("' ' (32, 0x20)", Print(' '));
296 EXPECT_EQ("'a' (97, 0x61)", Print('a'));
300 TEST(PrintCharTest, SignedChar) {
301 EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0')));
302 EXPECT_EQ("'\\xCE' (-50)",
303 Print(static_cast<signed char>(-50)));
307 TEST(PrintCharTest, UnsignedChar) {
308 EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0')));
309 EXPECT_EQ("'b' (98, 0x62)",
310 Print(static_cast<unsigned char>('b')));
313 // Tests printing other simple, built-in types.
316 TEST(PrintBuiltInTypeTest, Bool) {
317 EXPECT_EQ("false", Print(false));
318 EXPECT_EQ("true", Print(true));
322 TEST(PrintBuiltInTypeTest, Wchar_t) {
323 EXPECT_EQ("L'\\0'", Print(L'\0'));
324 EXPECT_EQ("L'\\'' (39, 0x27)", Print(L'\''));
325 EXPECT_EQ("L'\"' (34, 0x22)", Print(L'"'));
326 EXPECT_EQ("L'?' (63, 0x3F)", Print(L'?'));
327 EXPECT_EQ("L'\\\\' (92, 0x5C)", Print(L'\\'));
328 EXPECT_EQ("L'\\a' (7)", Print(L'\a'));
329 EXPECT_EQ("L'\\b' (8)", Print(L'\b'));
330 EXPECT_EQ("L'\\f' (12, 0xC)", Print(L'\f'));
331 EXPECT_EQ("L'\\n' (10, 0xA)", Print(L'\n'));
332 EXPECT_EQ("L'\\r' (13, 0xD)", Print(L'\r'));
333 EXPECT_EQ("L'\\t' (9)", Print(L'\t'));
334 EXPECT_EQ("L'\\v' (11, 0xB)", Print(L'\v'));
335 EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F'));
336 EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF'));
337 EXPECT_EQ("L' ' (32, 0x20)", Print(L' '));
338 EXPECT_EQ("L'a' (97, 0x61)", Print(L'a'));
339 EXPECT_EQ("L'\\x576' (1398)", Print(static_cast<wchar_t>(0x576)));
340 EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast<wchar_t>(0xC74D)));
343 // Test that Int64 provides more storage than wchar_t.
344 TEST(PrintTypeSizeTest, Wchar_t) {
345 EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64));
348 // Various integer types.
349 TEST(PrintBuiltInTypeTest, Integer) {
350 EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255))); // uint8
351 EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128))); // int8
352 EXPECT_EQ("65535", Print(USHRT_MAX)); // uint16
353 EXPECT_EQ("-32768", Print(SHRT_MIN)); // int16
354 EXPECT_EQ("4294967295", Print(UINT_MAX)); // uint32
355 EXPECT_EQ("-2147483648", Print(INT_MIN)); // int32
356 EXPECT_EQ("18446744073709551615",
357 Print(static_cast<testing::internal::UInt64>(-1))); // uint64
358 EXPECT_EQ("-9223372036854775808",
359 Print(static_cast<testing::internal::Int64>(1) << 63)); // int64
363 TEST(PrintBuiltInTypeTest, Size_t) {
364 EXPECT_EQ("1", Print(sizeof('a'))); // size_t.
365 #if !GTEST_OS_WINDOWS
366 // Windows has no ssize_t type.
367 EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2))); // ssize_t.
368 #endif // !GTEST_OS_WINDOWS
372 TEST(PrintBuiltInTypeTest, FloatingPoints) {
373 EXPECT_EQ("1.5", Print(1.5f)); // float
374 EXPECT_EQ("-2.5", Print(-2.5)); // double
377 // Since ::std::stringstream::operator<<(const void *) formats the pointer
378 // output differently with different compilers, we have to create the expected
379 // output first and use it as our expectation.
380 static std::string PrintPointer(const void* p) {
381 ::std::stringstream expected_result_stream;
382 expected_result_stream << p;
383 return expected_result_stream.str();
386 // Tests printing C strings.
389 TEST(PrintCStringTest, Const) {
390 const char* p = "World";
391 EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p));
395 TEST(PrintCStringTest, NonConst) {
397 EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"",
398 Print(static_cast<char*>(p)));
402 TEST(PrintCStringTest, Null) {
403 const char* p = nullptr;
404 EXPECT_EQ("NULL", Print(p));
407 // Tests that C strings are escaped properly.
408 TEST(PrintCStringTest, EscapesProperly) {
409 const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
410 EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f"
411 "\\n\\r\\t\\v\\x7F\\xFF a\"",
415 // MSVC compiler can be configured to define whar_t as a typedef
416 // of unsigned short. Defining an overload for const wchar_t* in that case
417 // would cause pointers to unsigned shorts be printed as wide strings,
418 // possibly accessing more memory than intended and causing invalid
419 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
420 // wchar_t is implemented as a native type.
421 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
424 TEST(PrintWideCStringTest, Const) {
425 const wchar_t* p = L"World";
426 EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p));
430 TEST(PrintWideCStringTest, NonConst) {
432 EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"",
433 Print(static_cast<wchar_t*>(p)));
436 // NULL wide C string.
437 TEST(PrintWideCStringTest, Null) {
438 const wchar_t* p = nullptr;
439 EXPECT_EQ("NULL", Print(p));
442 // Tests that wide C strings are escaped properly.
443 TEST(PrintWideCStringTest, EscapesProperly) {
444 const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r',
445 '\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'};
446 EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f"
447 "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
448 Print(static_cast<const wchar_t*>(s)));
450 #endif // native wchar_t
452 // Tests printing pointers to other char types.
455 TEST(PrintCharPointerTest, SignedChar) {
456 signed char* p = reinterpret_cast<signed char*>(0x1234);
457 EXPECT_EQ(PrintPointer(p), Print(p));
459 EXPECT_EQ("NULL", Print(p));
462 // const signed char*.
463 TEST(PrintCharPointerTest, ConstSignedChar) {
464 signed char* p = reinterpret_cast<signed char*>(0x1234);
465 EXPECT_EQ(PrintPointer(p), Print(p));
467 EXPECT_EQ("NULL", Print(p));
471 TEST(PrintCharPointerTest, UnsignedChar) {
472 unsigned char* p = reinterpret_cast<unsigned char*>(0x1234);
473 EXPECT_EQ(PrintPointer(p), Print(p));
475 EXPECT_EQ("NULL", Print(p));
478 // const unsigned char*.
479 TEST(PrintCharPointerTest, ConstUnsignedChar) {
480 const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234);
481 EXPECT_EQ(PrintPointer(p), Print(p));
483 EXPECT_EQ("NULL", Print(p));
486 // Tests printing pointers to simple, built-in types.
489 TEST(PrintPointerToBuiltInTypeTest, Bool) {
490 bool* p = reinterpret_cast<bool*>(0xABCD);
491 EXPECT_EQ(PrintPointer(p), Print(p));
493 EXPECT_EQ("NULL", Print(p));
497 TEST(PrintPointerToBuiltInTypeTest, Void) {
498 void* p = reinterpret_cast<void*>(0xABCD);
499 EXPECT_EQ(PrintPointer(p), Print(p));
501 EXPECT_EQ("NULL", Print(p));
505 TEST(PrintPointerToBuiltInTypeTest, ConstVoid) {
506 const void* p = reinterpret_cast<const void*>(0xABCD);
507 EXPECT_EQ(PrintPointer(p), Print(p));
509 EXPECT_EQ("NULL", Print(p));
512 // Tests printing pointers to pointers.
513 TEST(PrintPointerToPointerTest, IntPointerPointer) {
514 int** p = reinterpret_cast<int**>(0xABCD);
515 EXPECT_EQ(PrintPointer(p), Print(p));
517 EXPECT_EQ("NULL", Print(p));
520 // Tests printing (non-member) function pointers.
522 void MyFunction(int /* n */) {}
524 TEST(PrintPointerTest, NonMemberFunctionPointer) {
525 // We cannot directly cast &MyFunction to const void* because the
526 // standard disallows casting between pointers to functions and
527 // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
530 PrintPointer(reinterpret_cast<const void*>(
531 reinterpret_cast<internal::BiggestInt>(&MyFunction))),
533 int (*p)(bool) = NULL; // NOLINT
534 EXPECT_EQ("NULL", Print(p));
537 // An assertion predicate determining whether a one string is a prefix for
539 template <typename StringType>
540 AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
541 if (str.find(prefix, 0) == 0)
542 return AssertionSuccess();
544 const bool is_wide_string = sizeof(prefix[0]) > 1;
545 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
546 return AssertionFailure()
547 << begin_string_quote << prefix << "\" is not a prefix of "
548 << begin_string_quote << str << "\"\n";
551 // Tests printing member variable pointers. Although they are called
552 // pointers, they don't point to a location in the address space.
553 // Their representation is implementation-defined. Thus they will be
554 // printed as raw bytes.
559 int MyMethod(char x) { return x + 1; }
560 virtual char MyVirtualMethod(int /* n */) { return 'a'; }
565 TEST(PrintPointerTest, MemberVariablePointer) {
566 EXPECT_TRUE(HasPrefix(Print(&Foo::value),
567 Print(sizeof(&Foo::value)) + "-byte object "));
568 int Foo::*p = NULL; // NOLINT
569 EXPECT_TRUE(HasPrefix(Print(p),
570 Print(sizeof(p)) + "-byte object "));
573 // Tests printing member function pointers. Although they are called
574 // pointers, they don't point to a location in the address space.
575 // Their representation is implementation-defined. Thus they will be
576 // printed as raw bytes.
577 TEST(PrintPointerTest, MemberFunctionPointer) {
578 EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod),
579 Print(sizeof(&Foo::MyMethod)) + "-byte object "));
581 HasPrefix(Print(&Foo::MyVirtualMethod),
582 Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
583 int (Foo::*p)(char) = NULL; // NOLINT
584 EXPECT_TRUE(HasPrefix(Print(p),
585 Print(sizeof(p)) + "-byte object "));
588 // Tests printing C arrays.
590 // The difference between this and Print() is that it ensures that the
591 // argument is a reference to an array.
592 template <typename T, size_t N>
593 std::string PrintArrayHelper(T (&a)[N]) {
597 // One-dimensional array.
598 TEST(PrintArrayTest, OneDimensionalArray) {
599 int a[5] = { 1, 2, 3, 4, 5 };
600 EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
603 // Two-dimensional array.
604 TEST(PrintArrayTest, TwoDimensionalArray) {
609 EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
612 // Array of const elements.
613 TEST(PrintArrayTest, ConstArray) {
614 const bool a[1] = { false };
615 EXPECT_EQ("{ false }", PrintArrayHelper(a));
618 // char array without terminating NUL.
619 TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {
620 // Array a contains '\0' in the middle and doesn't end with '\0'.
621 char a[] = { 'H', '\0', 'i' };
622 EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
625 // const char array with terminating NUL.
626 TEST(PrintArrayTest, ConstCharArrayWithTerminatingNul) {
627 const char a[] = "\0Hi";
628 EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a));
631 // const wchar_t array without terminating NUL.
632 TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) {
633 // Array a contains '\0' in the middle and doesn't end with '\0'.
634 const wchar_t a[] = { L'H', L'\0', L'i' };
635 EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
638 // wchar_t array with terminating NUL.
639 TEST(PrintArrayTest, WConstCharArrayWithTerminatingNul) {
640 const wchar_t a[] = L"\0Hi";
641 EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a));
645 TEST(PrintArrayTest, ObjectArray) {
646 std::string a[3] = {"Hi", "Hello", "Ni hao"};
647 EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a));
650 // Array with many elements.
651 TEST(PrintArrayTest, BigArray) {
652 int a[100] = { 1, 2, 3 };
653 EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }",
654 PrintArrayHelper(a));
657 // Tests printing ::string and ::std::string.
660 TEST(PrintStringTest, StringInStdNamespace) {
661 const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
662 const ::std::string str(s, sizeof(s));
663 EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
667 TEST(PrintStringTest, StringAmbiguousHex) {
668 // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of:
669 // '\x6', '\x6B', or '\x6BA'.
671 // a hex escaping sequence following by a decimal digit
672 EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3")));
673 // a hex escaping sequence following by a hex digit (lower-case)
674 EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas")));
675 // a hex escaping sequence following by a hex digit (upper-case)
676 EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA")));
677 // a hex escaping sequence following by a non-xdigit
678 EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
681 // Tests printing ::std::wstring.
682 #if GTEST_HAS_STD_WSTRING
684 TEST(PrintWideStringTest, StringInStdNamespace) {
685 const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
686 const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t));
687 EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
688 "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
692 TEST(PrintWideStringTest, StringAmbiguousHex) {
693 // same for wide strings.
694 EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3")));
695 EXPECT_EQ("L\"mm\\x6\" L\"bananas\"",
696 Print(::std::wstring(L"mm\x6" L"bananas")));
697 EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"",
698 Print(::std::wstring(L"NOM\x6" L"BANANA")));
699 EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
701 #endif // GTEST_HAS_STD_WSTRING
703 // Tests printing types that support generic streaming (i.e. streaming
704 // to std::basic_ostream<Char, CharTraits> for any valid Char and
705 // CharTraits types).
707 // Tests printing a non-template type that supports generic streaming.
709 class AllowsGenericStreaming {};
711 template <typename Char, typename CharTraits>
712 std::basic_ostream<Char, CharTraits>& operator<<(
713 std::basic_ostream<Char, CharTraits>& os,
714 const AllowsGenericStreaming& /* a */) {
715 return os << "AllowsGenericStreaming";
718 TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) {
719 AllowsGenericStreaming a;
720 EXPECT_EQ("AllowsGenericStreaming", Print(a));
723 // Tests printing a template type that supports generic streaming.
725 template <typename T>
726 class AllowsGenericStreamingTemplate {};
728 template <typename Char, typename CharTraits, typename T>
729 std::basic_ostream<Char, CharTraits>& operator<<(
730 std::basic_ostream<Char, CharTraits>& os,
731 const AllowsGenericStreamingTemplate<T>& /* a */) {
732 return os << "AllowsGenericStreamingTemplate";
735 TEST(PrintTypeWithGenericStreamingTest, TemplateType) {
736 AllowsGenericStreamingTemplate<int> a;
737 EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a));
740 // Tests printing a type that supports generic streaming and can be
741 // implicitly converted to another printable type.
743 template <typename T>
744 class AllowsGenericStreamingAndImplicitConversionTemplate {
746 operator bool() const { return false; }
749 template <typename Char, typename CharTraits, typename T>
750 std::basic_ostream<Char, CharTraits>& operator<<(
751 std::basic_ostream<Char, CharTraits>& os,
752 const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) {
753 return os << "AllowsGenericStreamingAndImplicitConversionTemplate";
756 TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
757 AllowsGenericStreamingAndImplicitConversionTemplate<int> a;
758 EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
763 // Tests printing ::absl::string_view.
765 TEST(PrintStringViewTest, SimpleStringView) {
766 const ::absl::string_view sp = "Hello";
767 EXPECT_EQ("\"Hello\"", Print(sp));
770 TEST(PrintStringViewTest, UnprintableCharacters) {
771 const char str[] = "NUL (\0) and \r\t";
772 const ::absl::string_view sp(str, sizeof(str) - 1);
773 EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
776 #endif // GTEST_HAS_ABSL
778 // Tests printing STL containers.
780 TEST(PrintStlContainerTest, EmptyDeque) {
782 EXPECT_EQ("{}", Print(empty));
785 TEST(PrintStlContainerTest, NonEmptyDeque) {
786 deque<int> non_empty;
787 non_empty.push_back(1);
788 non_empty.push_back(3);
789 EXPECT_EQ("{ 1, 3 }", Print(non_empty));
793 TEST(PrintStlContainerTest, OneElementHashMap) {
794 ::std::unordered_map<int, char> map1;
796 EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1));
799 TEST(PrintStlContainerTest, HashMultiMap) {
800 ::std::unordered_multimap<int, bool> map1;
801 map1.insert(make_pair(5, true));
802 map1.insert(make_pair(5, false));
804 // Elements of hash_multimap can be printed in any order.
805 const std::string result = Print(map1);
806 EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
807 result == "{ (5, false), (5, true) }")
808 << " where Print(map1) returns \"" << result << "\".";
813 TEST(PrintStlContainerTest, HashSet) {
814 ::std::unordered_set<int> set1;
816 EXPECT_EQ("{ 1 }", Print(set1));
819 TEST(PrintStlContainerTest, HashMultiSet) {
821 int a[kSize] = { 1, 1, 2, 5, 1 };
822 ::std::unordered_multiset<int> set1(a, a + kSize);
824 // Elements of hash_multiset can be printed in any order.
825 const std::string result = Print(set1);
826 const std::string expected_pattern = "{ d, d, d, d, d }"; // d means a digit.
828 // Verifies the result matches the expected pattern; also extracts
829 // the numbers in the result.
830 ASSERT_EQ(expected_pattern.length(), result.length());
831 std::vector<int> numbers;
832 for (size_t i = 0; i != result.length(); i++) {
833 if (expected_pattern[i] == 'd') {
834 ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
835 numbers.push_back(result[i] - '0');
837 EXPECT_EQ(expected_pattern[i], result[i]) << " where result is "
842 // Makes sure the result contains the right numbers.
843 std::sort(numbers.begin(), numbers.end());
844 std::sort(a, a + kSize);
845 EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
849 TEST(PrintStlContainerTest, List) {
850 const std::string a[] = {"hello", "world"};
851 const list<std::string> strings(a, a + 2);
852 EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings));
855 TEST(PrintStlContainerTest, Map) {
860 EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1));
863 TEST(PrintStlContainerTest, MultiMap) {
864 multimap<bool, int> map1;
865 // The make_pair template function would deduce the type as
866 // pair<bool, int> here, and since the key part in a multimap has to
867 // be constant, without a templated ctor in the pair class (as in
868 // libCstd on Solaris), make_pair call would fail to compile as no
869 // implicit conversion is found. Thus explicit typename is used
871 map1.insert(pair<const bool, int>(true, 0));
872 map1.insert(pair<const bool, int>(true, 1));
873 map1.insert(pair<const bool, int>(false, 2));
874 EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1));
877 TEST(PrintStlContainerTest, Set) {
878 const unsigned int a[] = { 3, 0, 5 };
879 set<unsigned int> set1(a, a + 3);
880 EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
883 TEST(PrintStlContainerTest, MultiSet) {
884 const int a[] = { 1, 1, 2, 5, 1 };
885 multiset<int> set1(a, a + 5);
886 EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
890 TEST(PrintStlContainerTest, SinglyLinkedList) {
891 int a[] = { 9, 2, 8 };
892 const std::forward_list<int> ints(a, a + 3);
893 EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
896 TEST(PrintStlContainerTest, Pair) {
897 pair<const bool, int> p(true, 5);
898 EXPECT_EQ("(true, 5)", Print(p));
901 TEST(PrintStlContainerTest, Vector) {
905 EXPECT_EQ("{ 1, 2 }", Print(v));
908 TEST(PrintStlContainerTest, LongSequence) {
909 const int a[100] = { 1, 2, 3 };
910 const vector<int> v(a, a + 100);
911 EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
912 "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v));
915 TEST(PrintStlContainerTest, NestedContainer) {
916 const int a1[] = { 1, 2 };
917 const int a2[] = { 3, 4, 5 };
918 const list<int> l1(a1, a1 + 2);
919 const list<int> l2(a2, a2 + 3);
921 vector<list<int> > v;
924 EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
927 TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
928 const int a[3] = { 1, 2, 3 };
929 NativeArray<int> b(a, 3, RelationToSourceReference());
930 EXPECT_EQ("{ 1, 2, 3 }", Print(b));
933 TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
934 const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
935 NativeArray<int[3]> b(a, 2, RelationToSourceReference());
936 EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
939 // Tests that a class named iterator isn't treated as a container.
945 TEST(PrintStlContainerTest, Iterator) {
947 EXPECT_EQ("1-byte object <00>", Print(it));
950 // Tests that a class named const_iterator isn't treated as a container.
952 struct const_iterator {
956 TEST(PrintStlContainerTest, ConstIterator) {
957 const_iterator it = {};
958 EXPECT_EQ("1-byte object <00>", Print(it));
961 // Tests printing ::std::tuples.
963 // Tuples of various arities.
964 TEST(PrintStdTupleTest, VariousSizes) {
966 EXPECT_EQ("()", Print(t0));
968 ::std::tuple<int> t1(5);
969 EXPECT_EQ("(5)", Print(t1));
971 ::std::tuple<char, bool> t2('a', true);
972 EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
974 ::std::tuple<bool, int, int> t3(false, 2, 3);
975 EXPECT_EQ("(false, 2, 3)", Print(t3));
977 ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4);
978 EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
980 const char* const str = "8";
981 ::std::tuple<bool, char, short, testing::internal::Int32, // NOLINT
982 testing::internal::Int64, float, double, const char*, void*,
984 t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT
986 EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
987 " pointing to \"8\", NULL, \"10\")",
992 TEST(PrintStdTupleTest, NestedTuple) {
993 ::std::tuple< ::std::tuple<int, bool>, char> nested(
994 ::std::make_tuple(5, true), 'a');
995 EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
998 TEST(PrintNullptrT, Basic) {
999 EXPECT_EQ("(nullptr)", Print(nullptr));
1002 TEST(PrintReferenceWrapper, Printable) {
1004 EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::ref(x)));
1005 EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::cref(x)));
1008 TEST(PrintReferenceWrapper, Unprintable) {
1009 ::foo::UnprintableInFoo up;
1011 "@" + PrintPointer(&up) +
1012 " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1013 Print(std::ref(up)));
1015 "@" + PrintPointer(&up) +
1016 " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1017 Print(std::cref(up)));
1020 // Tests printing user-defined unprintable types.
1022 // Unprintable types in the global namespace.
1023 TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
1024 EXPECT_EQ("1-byte object <00>",
1025 Print(UnprintableTemplateInGlobal<char>()));
1028 // Unprintable types in a user namespace.
1029 TEST(PrintUnprintableTypeTest, InUserNamespace) {
1030 EXPECT_EQ("16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1031 Print(::foo::UnprintableInFoo()));
1034 // Unprintable types are that too big to be printed completely.
1037 Big() { memset(array, 0, sizeof(array)); }
1041 TEST(PrintUnpritableTypeTest, BigObject) {
1042 EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
1043 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1044 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1045 "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
1046 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1047 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1048 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
1052 // Tests printing user-defined streamable types.
1054 // Streamable types in the global namespace.
1055 TEST(PrintStreamableTypeTest, InGlobalNamespace) {
1056 StreamableInGlobal x;
1057 EXPECT_EQ("StreamableInGlobal", Print(x));
1058 EXPECT_EQ("StreamableInGlobal*", Print(&x));
1061 // Printable template types in a user namespace.
1062 TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
1063 EXPECT_EQ("StreamableTemplateInFoo: 0",
1064 Print(::foo::StreamableTemplateInFoo<int>()));
1067 // Tests printing a user-defined recursive container type that has a <<
1069 TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
1071 EXPECT_EQ("Streamable-PathLike", Print(x));
1072 const ::foo::PathLike cx;
1073 EXPECT_EQ("Streamable-PathLike", Print(cx));
1076 // Tests printing user-defined types that have a PrintTo() function.
1077 TEST(PrintPrintableTypeTest, InUserNamespace) {
1078 EXPECT_EQ("PrintableViaPrintTo: 0",
1079 Print(::foo::PrintableViaPrintTo()));
1082 // Tests printing a pointer to a user-defined type that has a <<
1083 // operator for its pointer.
1084 TEST(PrintPrintableTypeTest, PointerInUserNamespace) {
1085 ::foo::PointerPrintable x;
1086 EXPECT_EQ("PointerPrintable*", Print(&x));
1089 // Tests printing user-defined class template that have a PrintTo() function.
1090 TEST(PrintPrintableTypeTest, TemplateInUserNamespace) {
1091 EXPECT_EQ("PrintableViaPrintToTemplate: 5",
1092 Print(::foo::PrintableViaPrintToTemplate<int>(5)));
1095 // Tests that the universal printer prints both the address and the
1096 // value of a reference.
1097 TEST(PrintReferenceTest, PrintsAddressAndValue) {
1099 EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
1105 EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
1108 const ::foo::UnprintableInFoo x;
1109 EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object "
1110 "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1114 // Tests that the universal printer prints a function pointer passed by
1116 TEST(PrintReferenceTest, HandlesFunctionPointer) {
1117 void (*fp)(int n) = &MyFunction;
1118 const std::string fp_pointer_string =
1119 PrintPointer(reinterpret_cast<const void*>(&fp));
1120 // We cannot directly cast &MyFunction to const void* because the
1121 // standard disallows casting between pointers to functions and
1122 // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
1124 const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(
1125 reinterpret_cast<internal::BiggestInt>(fp)));
1126 EXPECT_EQ("@" + fp_pointer_string + " " + fp_string,
1130 // Tests that the universal printer prints a member function pointer
1131 // passed by reference.
1132 TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
1133 int (Foo::*p)(char ch) = &Foo::MyMethod;
1134 EXPECT_TRUE(HasPrefix(
1136 "@" + PrintPointer(reinterpret_cast<const void*>(&p)) + " " +
1137 Print(sizeof(p)) + "-byte object "));
1139 char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
1140 EXPECT_TRUE(HasPrefix(
1142 "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) + " " +
1143 Print(sizeof(p2)) + "-byte object "));
1146 // Tests that the universal printer prints a member variable pointer
1147 // passed by reference.
1148 TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
1149 int Foo::*p = &Foo::value; // NOLINT
1150 EXPECT_TRUE(HasPrefix(
1152 "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object "));
1155 // Tests that FormatForComparisonFailureMessage(), which is used to print
1156 // an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion
1157 // fails, formats the operand in the desired way.
1160 TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
1162 FormatForComparisonFailureMessage(123, 124).c_str());
1166 TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {
1168 EXPECT_EQ(PrintPointer(&n),
1169 FormatForComparisonFailureMessage(&n, &n).c_str());
1173 TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
1174 // In expression 'array == x', 'array' is compared by pointer.
1175 // Therefore we want to print an array operand as a pointer.
1176 int n[] = { 1, 2, 3 };
1177 EXPECT_EQ(PrintPointer(n),
1178 FormatForComparisonFailureMessage(n, n).c_str());
1181 // Tests formatting a char pointer when it's compared with another pointer.
1182 // In this case we want to print it as a raw pointer, as the comparison is by
1185 // char pointer vs pointer
1186 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
1187 // In expression 'p == x', where 'p' and 'x' are (const or not) char
1188 // pointers, the operands are compared by pointer. Therefore we
1189 // want to print 'p' as a pointer instead of a C string (we don't
1190 // even know if it's supposed to point to a valid C string).
1193 const char* s = "hello";
1194 EXPECT_EQ(PrintPointer(s),
1195 FormatForComparisonFailureMessage(s, s).c_str());
1199 EXPECT_EQ(PrintPointer(&ch),
1200 FormatForComparisonFailureMessage(&ch, &ch).c_str());
1203 // wchar_t pointer vs pointer
1204 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
1205 // In expression 'p == x', where 'p' and 'x' are (const or not) char
1206 // pointers, the operands are compared by pointer. Therefore we
1207 // want to print 'p' as a pointer instead of a wide C string (we don't
1208 // even know if it's supposed to point to a valid wide C string).
1211 const wchar_t* s = L"hello";
1212 EXPECT_EQ(PrintPointer(s),
1213 FormatForComparisonFailureMessage(s, s).c_str());
1217 EXPECT_EQ(PrintPointer(&ch),
1218 FormatForComparisonFailureMessage(&ch, &ch).c_str());
1221 // Tests formatting a char pointer when it's compared to a string object.
1222 // In this case we want to print the char pointer as a C string.
1224 // char pointer vs std::string
1225 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) {
1226 const char* s = "hello \"world";
1227 EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped.
1228 FormatForComparisonFailureMessage(s, ::std::string()).c_str());
1231 char str[] = "hi\1";
1233 EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped.
1234 FormatForComparisonFailureMessage(p, ::std::string()).c_str());
1237 #if GTEST_HAS_STD_WSTRING
1238 // wchar_t pointer vs std::wstring
1239 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) {
1240 const wchar_t* s = L"hi \"world";
1241 EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped.
1242 FormatForComparisonFailureMessage(s, ::std::wstring()).c_str());
1245 wchar_t str[] = L"hi\1";
1247 EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped.
1248 FormatForComparisonFailureMessage(p, ::std::wstring()).c_str());
1252 // Tests formatting a char array when it's compared with a pointer or array.
1253 // In this case we want to print the array as a row pointer, as the comparison
1256 // char array vs pointer
1257 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) {
1258 char str[] = "hi \"world\"";
1260 EXPECT_EQ(PrintPointer(str),
1261 FormatForComparisonFailureMessage(str, p).c_str());
1264 // char array vs char array
1265 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) {
1266 const char str[] = "hi \"world\"";
1267 EXPECT_EQ(PrintPointer(str),
1268 FormatForComparisonFailureMessage(str, str).c_str());
1271 // wchar_t array vs pointer
1272 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) {
1273 wchar_t str[] = L"hi \"world\"";
1274 wchar_t* p = nullptr;
1275 EXPECT_EQ(PrintPointer(str),
1276 FormatForComparisonFailureMessage(str, p).c_str());
1279 // wchar_t array vs wchar_t array
1280 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) {
1281 const wchar_t str[] = L"hi \"world\"";
1282 EXPECT_EQ(PrintPointer(str),
1283 FormatForComparisonFailureMessage(str, str).c_str());
1286 // Tests formatting a char array when it's compared with a string object.
1287 // In this case we want to print the array as a C string.
1289 // char array vs std::string
1290 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) {
1291 const char str[] = "hi \"world\"";
1292 EXPECT_STREQ("\"hi \\\"world\\\"\"", // The content should be escaped.
1293 FormatForComparisonFailureMessage(str, ::std::string()).c_str());
1296 #if GTEST_HAS_STD_WSTRING
1297 // wchar_t array vs std::wstring
1298 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
1299 const wchar_t str[] = L"hi \"w\0rld\"";
1301 "L\"hi \\\"w\"", // The content should be escaped.
1302 // Embedded NUL terminates the string.
1303 FormatForComparisonFailureMessage(str, ::std::wstring()).c_str());
1307 // Useful for testing PrintToString(). We cannot use EXPECT_EQ()
1308 // there as its implementation uses PrintToString(). The caller must
1309 // ensure that 'value' has no side effect.
1310 #define EXPECT_PRINT_TO_STRING_(value, expected_string) \
1311 EXPECT_TRUE(PrintToString(value) == (expected_string)) \
1312 << " where " #value " prints as " << (PrintToString(value))
1314 TEST(PrintToStringTest, WorksForScalar) {
1315 EXPECT_PRINT_TO_STRING_(123, "123");
1318 TEST(PrintToStringTest, WorksForPointerToConstChar) {
1319 const char* p = "hello";
1320 EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1323 TEST(PrintToStringTest, WorksForPointerToNonConstChar) {
1326 EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1329 TEST(PrintToStringTest, EscapesForPointerToConstChar) {
1330 const char* p = "hello\n";
1331 EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\"");
1334 TEST(PrintToStringTest, EscapesForPointerToNonConstChar) {
1335 char s[] = "hello\1";
1337 EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\"");
1340 TEST(PrintToStringTest, WorksForArray) {
1341 int n[3] = { 1, 2, 3 };
1342 EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }");
1345 TEST(PrintToStringTest, WorksForCharArray) {
1347 EXPECT_PRINT_TO_STRING_(s, "\"hello\"");
1350 TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {
1351 const char str_with_nul[] = "hello\0 world";
1352 EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\"");
1354 char mutable_str_with_nul[] = "hello\0 world";
1355 EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\"");
1358 TEST(PrintToStringTest, ContainsNonLatin) {
1359 // Sanity test with valid UTF-8. Prints both in hex and as text.
1360 std::string non_ascii_str = ::std::string("오전 4:30");
1361 EXPECT_PRINT_TO_STRING_(non_ascii_str,
1362 "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n"
1363 " As Text: \"오전 4:30\"");
1364 non_ascii_str = ::std::string("From ä — ẑ");
1365 EXPECT_PRINT_TO_STRING_(non_ascii_str,
1366 "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\""
1367 "\n As Text: \"From ä — ẑ\"");
1370 TEST(IsValidUTF8Test, IllFormedUTF8) {
1371 // The following test strings are ill-formed UTF-8 and are printed
1372 // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is
1373 // expected to fail, thus output does not contain "As Text:".
1375 static const char *const kTestdata[][2] = {
1376 // 2-byte lead byte followed by a single-byte character.
1377 {"\xC3\x74", "\"\\xC3t\""},
1378 // Valid 2-byte character followed by an orphan trail byte.
1379 {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""},
1380 // Lead byte without trail byte.
1381 {"abc\xC3", "\"abc\\xC3\""},
1382 // 3-byte lead byte, single-byte character, orphan trail byte.
1383 {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""},
1384 // Truncated 3-byte character.
1385 {"\xE2\x80", "\"\\xE2\\x80\""},
1386 // Truncated 3-byte character followed by valid 2-byte char.
1387 {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""},
1388 // Truncated 3-byte character followed by a single-byte character.
1389 {"\xE2\x80\x7A", "\"\\xE2\\x80z\""},
1390 // 3-byte lead byte followed by valid 3-byte character.
1391 {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""},
1392 // 4-byte lead byte followed by valid 3-byte character.
1393 {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""},
1394 // Truncated 4-byte character.
1395 {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""},
1396 // Invalid UTF-8 byte sequences embedded in other chars.
1397 {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""},
1398 {"abc\xC3\x84\xE2\x80\xC3\x84xyz",
1399 "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""},
1400 // Non-shortest UTF-8 byte sequences are also ill-formed.
1401 // The classics: xC0, xC1 lead byte.
1402 {"\xC0\x80", "\"\\xC0\\x80\""},
1403 {"\xC1\x81", "\"\\xC1\\x81\""},
1404 // Non-shortest sequences.
1405 {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
1406 {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
1407 // Last valid code point before surrogate range, should be printed as text,
1409 {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"\""},
1410 // Start of surrogate lead. Surrogates are not printed as text.
1411 {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""},
1412 // Last non-private surrogate lead.
1413 {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""},
1414 // First private-use surrogate lead.
1415 {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""},
1416 // Last private-use surrogate lead.
1417 {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
1418 // Mid-point of surrogate trail.
1419 {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
1420 // First valid code point after surrogate range, should be printed as text,
1422 {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""}
1425 for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) {
1426 EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
1430 #undef EXPECT_PRINT_TO_STRING_
1432 TEST(UniversalTersePrintTest, WorksForNonReference) {
1433 ::std::stringstream ss;
1434 UniversalTersePrint(123, &ss);
1435 EXPECT_EQ("123", ss.str());
1438 TEST(UniversalTersePrintTest, WorksForReference) {
1440 ::std::stringstream ss;
1441 UniversalTersePrint(n, &ss);
1442 EXPECT_EQ("123", ss.str());
1445 TEST(UniversalTersePrintTest, WorksForCString) {
1446 const char* s1 = "abc";
1447 ::std::stringstream ss1;
1448 UniversalTersePrint(s1, &ss1);
1449 EXPECT_EQ("\"abc\"", ss1.str());
1451 char* s2 = const_cast<char*>(s1);
1452 ::std::stringstream ss2;
1453 UniversalTersePrint(s2, &ss2);
1454 EXPECT_EQ("\"abc\"", ss2.str());
1456 const char* s3 = nullptr;
1457 ::std::stringstream ss3;
1458 UniversalTersePrint(s3, &ss3);
1459 EXPECT_EQ("NULL", ss3.str());
1462 TEST(UniversalPrintTest, WorksForNonReference) {
1463 ::std::stringstream ss;
1464 UniversalPrint(123, &ss);
1465 EXPECT_EQ("123", ss.str());
1468 TEST(UniversalPrintTest, WorksForReference) {
1470 ::std::stringstream ss;
1471 UniversalPrint(n, &ss);
1472 EXPECT_EQ("123", ss.str());
1475 TEST(UniversalPrintTest, WorksForCString) {
1476 const char* s1 = "abc";
1477 ::std::stringstream ss1;
1478 UniversalPrint(s1, &ss1);
1479 EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str()));
1481 char* s2 = const_cast<char*>(s1);
1482 ::std::stringstream ss2;
1483 UniversalPrint(s2, &ss2);
1484 EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str()));
1486 const char* s3 = nullptr;
1487 ::std::stringstream ss3;
1488 UniversalPrint(s3, &ss3);
1489 EXPECT_EQ("NULL", ss3.str());
1492 TEST(UniversalPrintTest, WorksForCharArray) {
1493 const char str[] = "\"Line\0 1\"\nLine 2";
1494 ::std::stringstream ss1;
1495 UniversalPrint(str, &ss1);
1496 EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str());
1498 const char mutable_str[] = "\"Line\0 1\"\nLine 2";
1499 ::std::stringstream ss2;
1500 UniversalPrint(mutable_str, &ss2);
1501 EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str());
1504 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
1505 Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
1506 EXPECT_EQ(0u, result.size());
1509 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
1510 Strings result = UniversalTersePrintTupleFieldsToStrings(
1511 ::std::make_tuple(1));
1512 ASSERT_EQ(1u, result.size());
1513 EXPECT_EQ("1", result[0]);
1516 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
1517 Strings result = UniversalTersePrintTupleFieldsToStrings(
1518 ::std::make_tuple(1, 'a'));
1519 ASSERT_EQ(2u, result.size());
1520 EXPECT_EQ("1", result[0]);
1521 EXPECT_EQ("'a' (97, 0x61)", result[1]);
1524 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
1526 Strings result = UniversalTersePrintTupleFieldsToStrings(
1527 ::std::tuple<const int&, const char*>(n, "a"));
1528 ASSERT_EQ(2u, result.size());
1529 EXPECT_EQ("1", result[0]);
1530 EXPECT_EQ("\"a\"", result[1]);
1535 TEST(PrintOptionalTest, Basic) {
1536 absl::optional<int> value;
1537 EXPECT_EQ("(nullopt)", PrintToString(value));
1539 EXPECT_EQ("(7)", PrintToString(value));
1540 EXPECT_EQ("(1.1)", PrintToString(absl::optional<double>{1.1}));
1541 EXPECT_EQ("(\"A\")", PrintToString(absl::optional<std::string>{"A"}));
1544 struct NonPrintable {
1545 unsigned char contents = 17;
1548 TEST(PrintOneofTest, Basic) {
1549 using Type = absl::variant<int, StreamableInGlobal, NonPrintable>;
1550 EXPECT_EQ("('int' with value 7)", PrintToString(Type(7)));
1551 EXPECT_EQ("('StreamableInGlobal' with value StreamableInGlobal)",
1552 PrintToString(Type(StreamableInGlobal{})));
1554 "('testing::gtest_printers_test::NonPrintable' with value 1-byte object "
1556 PrintToString(Type(NonPrintable{})));
1558 #endif // GTEST_HAS_ABSL
1563 * This is a synthetic pointer to a fixed size string.
1567 string_ptr(const char* data, size_t size) : data_(data), size_(size) {}
1569 string_ptr& operator++() noexcept {
1574 string_ref operator*() const noexcept;
1582 * This is a synthetic reference of a fixed size string.
1586 string_ref(const char* data, size_t size) : data_(data), size_(size) {}
1588 string_ptr operator&() const noexcept { return {data_, size_}; } // NOLINT
1590 bool operator==(const char* s) const noexcept {
1591 if (size_ > 0 && data_[size_ - 1] != 0) {
1592 return std::string(data_, size_) == std::string(s);
1594 return std::string(data_) == std::string(s);
1603 string_ref string_ptr::operator*() const noexcept { return {data_, size_}; }
1605 TEST(string_ref, compare) {
1606 const char* s = "alex\0davidjohn\0";
1607 string_ptr ptr(s, 5);
1608 EXPECT_EQ(*ptr, "alex");
1609 EXPECT_TRUE(*ptr == "alex");
1611 EXPECT_EQ(*ptr, "david");
1612 EXPECT_TRUE(*ptr == "david");
1614 EXPECT_EQ(*ptr, "john");
1619 } // namespace gtest_printers_test
1620 } // namespace testing