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.
48 #include "gtest/gtest-printers.h"
49 #include "gtest/gtest.h"
51 #if GTEST_HAS_UNORDERED_MAP_
52 # include <unordered_map> // NOLINT
53 #endif // GTEST_HAS_UNORDERED_MAP_
55 #if GTEST_HAS_UNORDERED_SET_
56 # include <unordered_set> // NOLINT
57 #endif // GTEST_HAS_UNORDERED_SET_
59 #if GTEST_HAS_STD_FORWARD_LIST_
60 # include <forward_list> // NOLINT
61 #endif // GTEST_HAS_STD_FORWARD_LIST_
63 // Some user-defined types for testing the universal value printer.
65 // An anonymous enum type.
71 // An enum without a user-defined printer.
72 enum EnumWithoutPrinter {
77 // An enum with a << operator.
78 enum EnumWithStreaming {
82 std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
83 return os << (e == kEWS1 ? "kEWS1" : "invalid");
86 // An enum with a PrintTo() function.
87 enum EnumWithPrintTo {
91 void PrintTo(EnumWithPrintTo e, std::ostream* os) {
92 *os << (e == kEWPT1 ? "kEWPT1" : "invalid");
95 // A class implicitly convertible to BiggestInt.
96 class BiggestIntConvertible {
98 operator ::testing::internal::BiggestInt() const { return 42; }
101 // A user-defined unprintable class template in the global namespace.
102 template <typename T>
103 class UnprintableTemplateInGlobal {
105 UnprintableTemplateInGlobal() : value_() {}
110 // A user-defined streamable type in the global namespace.
111 class StreamableInGlobal {
113 virtual ~StreamableInGlobal() {}
116 inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) {
117 os << "StreamableInGlobal";
120 void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) {
121 os << "StreamableInGlobal*";
126 // A user-defined unprintable type in a user namespace.
127 class UnprintableInFoo {
129 UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
130 double z() const { return z_; }
136 // A user-defined printable type in a user-chosen namespace.
137 struct PrintableViaPrintTo {
138 PrintableViaPrintTo() : value() {}
142 void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
143 *os << "PrintableViaPrintTo: " << x.value;
146 // A type with a user-defined << for printing its pointer.
147 struct PointerPrintable {
150 ::std::ostream& operator<<(::std::ostream& os,
151 const PointerPrintable* /* x */) {
152 return os << "PointerPrintable*";
155 // A user-defined printable class template in a user-chosen namespace.
156 template <typename T>
157 class PrintableViaPrintToTemplate {
159 explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
161 const T& value() const { return value_; }
166 template <typename T>
167 void PrintTo(const PrintableViaPrintToTemplate<T>& x, ::std::ostream* os) {
168 *os << "PrintableViaPrintToTemplate: " << x.value();
171 // A user-defined streamable class template in a user namespace.
172 template <typename T>
173 class StreamableTemplateInFoo {
175 StreamableTemplateInFoo() : value_() {}
177 const T& value() const { return value_; }
182 template <typename T>
183 inline ::std::ostream& operator<<(::std::ostream& os,
184 const StreamableTemplateInFoo<T>& x) {
185 return os << "StreamableTemplateInFoo: " << x.value();
188 // A user-defined streamable but recursivly-defined container type in
189 // a user namespace, it mimics therefore std::filesystem::path or
190 // boost::filesystem::path.
194 typedef PathLike value_type;
199 iterator begin() const { return iterator(); }
200 iterator end() const { return iterator(); }
202 friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) {
203 return os << "Streamable-PathLike";
210 namespace gtest_printers_test {
214 using ::std::make_pair;
216 using ::std::multimap;
217 using ::std::multiset;
221 using ::testing::PrintToString;
222 using ::testing::internal::FormatForComparisonFailureMessage;
223 using ::testing::internal::ImplicitCast_;
224 using ::testing::internal::NativeArray;
225 using ::testing::internal::RE;
226 using ::testing::internal::RelationToSourceReference;
227 using ::testing::internal::Strings;
228 using ::testing::internal::UniversalPrint;
229 using ::testing::internal::UniversalPrinter;
230 using ::testing::internal::UniversalTersePrint;
231 #if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
232 using ::testing::internal::UniversalTersePrintTupleFieldsToStrings;
235 // Prints a value to a string using the universal value printer. This
236 // is a helper for testing UniversalPrinter<T>::Print() for various types.
237 template <typename T>
238 std::string Print(const T& value) {
239 ::std::stringstream ss;
240 UniversalPrinter<T>::Print(value, &ss);
244 // Prints a value passed by reference to a string, using the universal
245 // value printer. This is a helper for testing
246 // UniversalPrinter<T&>::Print() for various types.
247 template <typename T>
248 std::string PrintByRef(const T& value) {
249 ::std::stringstream ss;
250 UniversalPrinter<T&>::Print(value, &ss);
254 // Tests printing various enum types.
256 TEST(PrintEnumTest, AnonymousEnum) {
257 EXPECT_EQ("-1", Print(kAE1));
258 EXPECT_EQ("1", Print(kAE2));
261 TEST(PrintEnumTest, EnumWithoutPrinter) {
262 EXPECT_EQ("-2", Print(kEWP1));
263 EXPECT_EQ("42", Print(kEWP2));
266 TEST(PrintEnumTest, EnumWithStreaming) {
267 EXPECT_EQ("kEWS1", Print(kEWS1));
268 EXPECT_EQ("invalid", Print(static_cast<EnumWithStreaming>(0)));
271 TEST(PrintEnumTest, EnumWithPrintTo) {
272 EXPECT_EQ("kEWPT1", Print(kEWPT1));
273 EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0)));
276 // Tests printing a class implicitly convertible to BiggestInt.
278 TEST(PrintClassTest, BiggestIntConvertible) {
279 EXPECT_EQ("42", Print(BiggestIntConvertible()));
282 // Tests printing various char types.
285 TEST(PrintCharTest, PlainChar) {
286 EXPECT_EQ("'\\0'", Print('\0'));
287 EXPECT_EQ("'\\'' (39, 0x27)", Print('\''));
288 EXPECT_EQ("'\"' (34, 0x22)", Print('"'));
289 EXPECT_EQ("'?' (63, 0x3F)", Print('?'));
290 EXPECT_EQ("'\\\\' (92, 0x5C)", Print('\\'));
291 EXPECT_EQ("'\\a' (7)", Print('\a'));
292 EXPECT_EQ("'\\b' (8)", Print('\b'));
293 EXPECT_EQ("'\\f' (12, 0xC)", Print('\f'));
294 EXPECT_EQ("'\\n' (10, 0xA)", Print('\n'));
295 EXPECT_EQ("'\\r' (13, 0xD)", Print('\r'));
296 EXPECT_EQ("'\\t' (9)", Print('\t'));
297 EXPECT_EQ("'\\v' (11, 0xB)", Print('\v'));
298 EXPECT_EQ("'\\x7F' (127)", Print('\x7F'));
299 EXPECT_EQ("'\\xFF' (255)", Print('\xFF'));
300 EXPECT_EQ("' ' (32, 0x20)", Print(' '));
301 EXPECT_EQ("'a' (97, 0x61)", Print('a'));
305 TEST(PrintCharTest, SignedChar) {
306 EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0')));
307 EXPECT_EQ("'\\xCE' (-50)",
308 Print(static_cast<signed char>(-50)));
312 TEST(PrintCharTest, UnsignedChar) {
313 EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0')));
314 EXPECT_EQ("'b' (98, 0x62)",
315 Print(static_cast<unsigned char>('b')));
318 // Tests printing other simple, built-in types.
321 TEST(PrintBuiltInTypeTest, Bool) {
322 EXPECT_EQ("false", Print(false));
323 EXPECT_EQ("true", Print(true));
327 TEST(PrintBuiltInTypeTest, Wchar_t) {
328 EXPECT_EQ("L'\\0'", Print(L'\0'));
329 EXPECT_EQ("L'\\'' (39, 0x27)", Print(L'\''));
330 EXPECT_EQ("L'\"' (34, 0x22)", Print(L'"'));
331 EXPECT_EQ("L'?' (63, 0x3F)", Print(L'?'));
332 EXPECT_EQ("L'\\\\' (92, 0x5C)", Print(L'\\'));
333 EXPECT_EQ("L'\\a' (7)", Print(L'\a'));
334 EXPECT_EQ("L'\\b' (8)", Print(L'\b'));
335 EXPECT_EQ("L'\\f' (12, 0xC)", Print(L'\f'));
336 EXPECT_EQ("L'\\n' (10, 0xA)", Print(L'\n'));
337 EXPECT_EQ("L'\\r' (13, 0xD)", Print(L'\r'));
338 EXPECT_EQ("L'\\t' (9)", Print(L'\t'));
339 EXPECT_EQ("L'\\v' (11, 0xB)", Print(L'\v'));
340 EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F'));
341 EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF'));
342 EXPECT_EQ("L' ' (32, 0x20)", Print(L' '));
343 EXPECT_EQ("L'a' (97, 0x61)", Print(L'a'));
344 EXPECT_EQ("L'\\x576' (1398)", Print(static_cast<wchar_t>(0x576)));
345 EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast<wchar_t>(0xC74D)));
348 // Test that Int64 provides more storage than wchar_t.
349 TEST(PrintTypeSizeTest, Wchar_t) {
350 EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64));
353 // Various integer types.
354 TEST(PrintBuiltInTypeTest, Integer) {
355 EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255))); // uint8
356 EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128))); // int8
357 EXPECT_EQ("65535", Print(USHRT_MAX)); // uint16
358 EXPECT_EQ("-32768", Print(SHRT_MIN)); // int16
359 EXPECT_EQ("4294967295", Print(UINT_MAX)); // uint32
360 EXPECT_EQ("-2147483648", Print(INT_MIN)); // int32
361 EXPECT_EQ("18446744073709551615",
362 Print(static_cast<testing::internal::UInt64>(-1))); // uint64
363 EXPECT_EQ("-9223372036854775808",
364 Print(static_cast<testing::internal::Int64>(1) << 63)); // int64
368 TEST(PrintBuiltInTypeTest, Size_t) {
369 EXPECT_EQ("1", Print(sizeof('a'))); // size_t.
370 #if !GTEST_OS_WINDOWS
371 // Windows has no ssize_t type.
372 EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2))); // ssize_t.
373 #endif // !GTEST_OS_WINDOWS
377 TEST(PrintBuiltInTypeTest, FloatingPoints) {
378 EXPECT_EQ("1.5", Print(1.5f)); // float
379 EXPECT_EQ("-2.5", Print(-2.5)); // double
382 // Since ::std::stringstream::operator<<(const void *) formats the pointer
383 // output differently with different compilers, we have to create the expected
384 // output first and use it as our expectation.
385 static std::string PrintPointer(const void* p) {
386 ::std::stringstream expected_result_stream;
387 expected_result_stream << p;
388 return expected_result_stream.str();
391 // Tests printing C strings.
394 TEST(PrintCStringTest, Const) {
395 const char* p = "World";
396 EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p));
400 TEST(PrintCStringTest, NonConst) {
402 EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"",
403 Print(static_cast<char*>(p)));
407 TEST(PrintCStringTest, Null) {
408 const char* p = NULL;
409 EXPECT_EQ("NULL", Print(p));
412 // Tests that C strings are escaped properly.
413 TEST(PrintCStringTest, EscapesProperly) {
414 const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
415 EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f"
416 "\\n\\r\\t\\v\\x7F\\xFF a\"",
420 // MSVC compiler can be configured to define whar_t as a typedef
421 // of unsigned short. Defining an overload for const wchar_t* in that case
422 // would cause pointers to unsigned shorts be printed as wide strings,
423 // possibly accessing more memory than intended and causing invalid
424 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
425 // wchar_t is implemented as a native type.
426 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
429 TEST(PrintWideCStringTest, Const) {
430 const wchar_t* p = L"World";
431 EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p));
435 TEST(PrintWideCStringTest, NonConst) {
437 EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"",
438 Print(static_cast<wchar_t*>(p)));
441 // NULL wide C string.
442 TEST(PrintWideCStringTest, Null) {
443 const wchar_t* p = NULL;
444 EXPECT_EQ("NULL", Print(p));
447 // Tests that wide C strings are escaped properly.
448 TEST(PrintWideCStringTest, EscapesProperly) {
449 const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r',
450 '\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'};
451 EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f"
452 "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
453 Print(static_cast<const wchar_t*>(s)));
455 #endif // native wchar_t
457 // Tests printing pointers to other char types.
460 TEST(PrintCharPointerTest, SignedChar) {
461 signed char* p = reinterpret_cast<signed char*>(0x1234);
462 EXPECT_EQ(PrintPointer(p), Print(p));
464 EXPECT_EQ("NULL", Print(p));
467 // const signed char*.
468 TEST(PrintCharPointerTest, ConstSignedChar) {
469 signed char* p = reinterpret_cast<signed char*>(0x1234);
470 EXPECT_EQ(PrintPointer(p), Print(p));
472 EXPECT_EQ("NULL", Print(p));
476 TEST(PrintCharPointerTest, UnsignedChar) {
477 unsigned char* p = reinterpret_cast<unsigned char*>(0x1234);
478 EXPECT_EQ(PrintPointer(p), Print(p));
480 EXPECT_EQ("NULL", Print(p));
483 // const unsigned char*.
484 TEST(PrintCharPointerTest, ConstUnsignedChar) {
485 const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234);
486 EXPECT_EQ(PrintPointer(p), Print(p));
488 EXPECT_EQ("NULL", Print(p));
491 // Tests printing pointers to simple, built-in types.
494 TEST(PrintPointerToBuiltInTypeTest, Bool) {
495 bool* p = reinterpret_cast<bool*>(0xABCD);
496 EXPECT_EQ(PrintPointer(p), Print(p));
498 EXPECT_EQ("NULL", Print(p));
502 TEST(PrintPointerToBuiltInTypeTest, Void) {
503 void* p = reinterpret_cast<void*>(0xABCD);
504 EXPECT_EQ(PrintPointer(p), Print(p));
506 EXPECT_EQ("NULL", Print(p));
510 TEST(PrintPointerToBuiltInTypeTest, ConstVoid) {
511 const void* p = reinterpret_cast<const void*>(0xABCD);
512 EXPECT_EQ(PrintPointer(p), Print(p));
514 EXPECT_EQ("NULL", Print(p));
517 // Tests printing pointers to pointers.
518 TEST(PrintPointerToPointerTest, IntPointerPointer) {
519 int** p = reinterpret_cast<int**>(0xABCD);
520 EXPECT_EQ(PrintPointer(p), Print(p));
522 EXPECT_EQ("NULL", Print(p));
525 // Tests printing (non-member) function pointers.
527 void MyFunction(int /* n */) {}
529 TEST(PrintPointerTest, NonMemberFunctionPointer) {
530 // We cannot directly cast &MyFunction to const void* because the
531 // standard disallows casting between pointers to functions and
532 // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
535 PrintPointer(reinterpret_cast<const void*>(
536 reinterpret_cast<internal::BiggestInt>(&MyFunction))),
538 int (*p)(bool) = NULL; // NOLINT
539 EXPECT_EQ("NULL", Print(p));
542 // An assertion predicate determining whether a one string is a prefix for
544 template <typename StringType>
545 AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
546 if (str.find(prefix, 0) == 0)
547 return AssertionSuccess();
549 const bool is_wide_string = sizeof(prefix[0]) > 1;
550 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
551 return AssertionFailure()
552 << begin_string_quote << prefix << "\" is not a prefix of "
553 << begin_string_quote << str << "\"\n";
556 // Tests printing member variable pointers. Although they are called
557 // pointers, they don't point to a location in the address space.
558 // Their representation is implementation-defined. Thus they will be
559 // printed as raw bytes.
564 int MyMethod(char x) { return x + 1; }
565 virtual char MyVirtualMethod(int /* n */) { return 'a'; }
570 TEST(PrintPointerTest, MemberVariablePointer) {
571 EXPECT_TRUE(HasPrefix(Print(&Foo::value),
572 Print(sizeof(&Foo::value)) + "-byte object "));
573 int Foo::*p = NULL; // NOLINT
574 EXPECT_TRUE(HasPrefix(Print(p),
575 Print(sizeof(p)) + "-byte object "));
578 // Tests printing member function pointers. Although they are called
579 // pointers, they don't point to a location in the address space.
580 // Their representation is implementation-defined. Thus they will be
581 // printed as raw bytes.
582 TEST(PrintPointerTest, MemberFunctionPointer) {
583 EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod),
584 Print(sizeof(&Foo::MyMethod)) + "-byte object "));
586 HasPrefix(Print(&Foo::MyVirtualMethod),
587 Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
588 int (Foo::*p)(char) = NULL; // NOLINT
589 EXPECT_TRUE(HasPrefix(Print(p),
590 Print(sizeof(p)) + "-byte object "));
593 // Tests printing C arrays.
595 // The difference between this and Print() is that it ensures that the
596 // argument is a reference to an array.
597 template <typename T, size_t N>
598 std::string PrintArrayHelper(T (&a)[N]) {
602 // One-dimensional array.
603 TEST(PrintArrayTest, OneDimensionalArray) {
604 int a[5] = { 1, 2, 3, 4, 5 };
605 EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
608 // Two-dimensional array.
609 TEST(PrintArrayTest, TwoDimensionalArray) {
614 EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
617 // Array of const elements.
618 TEST(PrintArrayTest, ConstArray) {
619 const bool a[1] = { false };
620 EXPECT_EQ("{ false }", PrintArrayHelper(a));
623 // char array without terminating NUL.
624 TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {
625 // Array a contains '\0' in the middle and doesn't end with '\0'.
626 char a[] = { 'H', '\0', 'i' };
627 EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
630 // const char array with terminating NUL.
631 TEST(PrintArrayTest, ConstCharArrayWithTerminatingNul) {
632 const char a[] = "\0Hi";
633 EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a));
636 // const wchar_t array without terminating NUL.
637 TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) {
638 // Array a contains '\0' in the middle and doesn't end with '\0'.
639 const wchar_t a[] = { L'H', L'\0', L'i' };
640 EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
643 // wchar_t array with terminating NUL.
644 TEST(PrintArrayTest, WConstCharArrayWithTerminatingNul) {
645 const wchar_t a[] = L"\0Hi";
646 EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a));
650 TEST(PrintArrayTest, ObjectArray) {
651 std::string a[3] = {"Hi", "Hello", "Ni hao"};
652 EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a));
655 // Array with many elements.
656 TEST(PrintArrayTest, BigArray) {
657 int a[100] = { 1, 2, 3 };
658 EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }",
659 PrintArrayHelper(a));
662 // Tests printing ::string and ::std::string.
664 #if GTEST_HAS_GLOBAL_STRING
666 TEST(PrintStringTest, StringInGlobalNamespace) {
667 const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
668 const ::string str(s, sizeof(s));
669 EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
672 #endif // GTEST_HAS_GLOBAL_STRING
675 TEST(PrintStringTest, StringInStdNamespace) {
676 const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
677 const ::std::string str(s, sizeof(s));
678 EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
682 TEST(PrintStringTest, StringAmbiguousHex) {
683 // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of:
684 // '\x6', '\x6B', or '\x6BA'.
686 // a hex escaping sequence following by a decimal digit
687 EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3")));
688 // a hex escaping sequence following by a hex digit (lower-case)
689 EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas")));
690 // a hex escaping sequence following by a hex digit (upper-case)
691 EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA")));
692 // a hex escaping sequence following by a non-xdigit
693 EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
696 // Tests printing ::wstring and ::std::wstring.
698 #if GTEST_HAS_GLOBAL_WSTRING
700 TEST(PrintWideStringTest, StringInGlobalNamespace) {
701 const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
702 const ::wstring str(s, sizeof(s)/sizeof(wchar_t));
703 EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
704 "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
707 #endif // GTEST_HAS_GLOBAL_WSTRING
709 #if GTEST_HAS_STD_WSTRING
711 TEST(PrintWideStringTest, StringInStdNamespace) {
712 const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
713 const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t));
714 EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
715 "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
719 TEST(PrintWideStringTest, StringAmbiguousHex) {
720 // same for wide strings.
721 EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3")));
722 EXPECT_EQ("L\"mm\\x6\" L\"bananas\"",
723 Print(::std::wstring(L"mm\x6" L"bananas")));
724 EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"",
725 Print(::std::wstring(L"NOM\x6" L"BANANA")));
726 EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
728 #endif // GTEST_HAS_STD_WSTRING
730 // Tests printing types that support generic streaming (i.e. streaming
731 // to std::basic_ostream<Char, CharTraits> for any valid Char and
732 // CharTraits types).
734 // Tests printing a non-template type that supports generic streaming.
736 class AllowsGenericStreaming {};
738 template <typename Char, typename CharTraits>
739 std::basic_ostream<Char, CharTraits>& operator<<(
740 std::basic_ostream<Char, CharTraits>& os,
741 const AllowsGenericStreaming& /* a */) {
742 return os << "AllowsGenericStreaming";
745 TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) {
746 AllowsGenericStreaming a;
747 EXPECT_EQ("AllowsGenericStreaming", Print(a));
750 // Tests printing a template type that supports generic streaming.
752 template <typename T>
753 class AllowsGenericStreamingTemplate {};
755 template <typename Char, typename CharTraits, typename T>
756 std::basic_ostream<Char, CharTraits>& operator<<(
757 std::basic_ostream<Char, CharTraits>& os,
758 const AllowsGenericStreamingTemplate<T>& /* a */) {
759 return os << "AllowsGenericStreamingTemplate";
762 TEST(PrintTypeWithGenericStreamingTest, TemplateType) {
763 AllowsGenericStreamingTemplate<int> a;
764 EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a));
767 // Tests printing a type that supports generic streaming and can be
768 // implicitly converted to another printable type.
770 template <typename T>
771 class AllowsGenericStreamingAndImplicitConversionTemplate {
773 operator bool() const { return false; }
776 template <typename Char, typename CharTraits, typename T>
777 std::basic_ostream<Char, CharTraits>& operator<<(
778 std::basic_ostream<Char, CharTraits>& os,
779 const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) {
780 return os << "AllowsGenericStreamingAndImplicitConversionTemplate";
783 TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
784 AllowsGenericStreamingAndImplicitConversionTemplate<int> a;
785 EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
790 // Tests printing ::absl::string_view.
792 TEST(PrintStringViewTest, SimpleStringView) {
793 const ::absl::string_view sp = "Hello";
794 EXPECT_EQ("\"Hello\"", Print(sp));
797 TEST(PrintStringViewTest, UnprintableCharacters) {
798 const char str[] = "NUL (\0) and \r\t";
799 const ::absl::string_view sp(str, sizeof(str) - 1);
800 EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
803 #endif // GTEST_HAS_ABSL
805 // Tests printing STL containers.
807 TEST(PrintStlContainerTest, EmptyDeque) {
809 EXPECT_EQ("{}", Print(empty));
812 TEST(PrintStlContainerTest, NonEmptyDeque) {
813 deque<int> non_empty;
814 non_empty.push_back(1);
815 non_empty.push_back(3);
816 EXPECT_EQ("{ 1, 3 }", Print(non_empty));
819 #if GTEST_HAS_UNORDERED_MAP_
821 TEST(PrintStlContainerTest, OneElementHashMap) {
822 ::std::unordered_map<int, char> map1;
824 EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1));
827 TEST(PrintStlContainerTest, HashMultiMap) {
828 ::std::unordered_multimap<int, bool> map1;
829 map1.insert(make_pair(5, true));
830 map1.insert(make_pair(5, false));
832 // Elements of hash_multimap can be printed in any order.
833 const std::string result = Print(map1);
834 EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
835 result == "{ (5, false), (5, true) }")
836 << " where Print(map1) returns \"" << result << "\".";
839 #endif // GTEST_HAS_UNORDERED_MAP_
841 #if GTEST_HAS_UNORDERED_SET_
843 TEST(PrintStlContainerTest, HashSet) {
844 ::std::unordered_set<int> set1;
846 EXPECT_EQ("{ 1 }", Print(set1));
849 TEST(PrintStlContainerTest, HashMultiSet) {
851 int a[kSize] = { 1, 1, 2, 5, 1 };
852 ::std::unordered_multiset<int> set1(a, a + kSize);
854 // Elements of hash_multiset can be printed in any order.
855 const std::string result = Print(set1);
856 const std::string expected_pattern = "{ d, d, d, d, d }"; // d means a digit.
858 // Verifies the result matches the expected pattern; also extracts
859 // the numbers in the result.
860 ASSERT_EQ(expected_pattern.length(), result.length());
861 std::vector<int> numbers;
862 for (size_t i = 0; i != result.length(); i++) {
863 if (expected_pattern[i] == 'd') {
864 ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
865 numbers.push_back(result[i] - '0');
867 EXPECT_EQ(expected_pattern[i], result[i]) << " where result is "
872 // Makes sure the result contains the right numbers.
873 std::sort(numbers.begin(), numbers.end());
874 std::sort(a, a + kSize);
875 EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
878 #endif // GTEST_HAS_UNORDERED_SET_
880 TEST(PrintStlContainerTest, List) {
881 const std::string a[] = {"hello", "world"};
882 const list<std::string> strings(a, a + 2);
883 EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings));
886 TEST(PrintStlContainerTest, Map) {
891 EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1));
894 TEST(PrintStlContainerTest, MultiMap) {
895 multimap<bool, int> map1;
896 // The make_pair template function would deduce the type as
897 // pair<bool, int> here, and since the key part in a multimap has to
898 // be constant, without a templated ctor in the pair class (as in
899 // libCstd on Solaris), make_pair call would fail to compile as no
900 // implicit conversion is found. Thus explicit typename is used
902 map1.insert(pair<const bool, int>(true, 0));
903 map1.insert(pair<const bool, int>(true, 1));
904 map1.insert(pair<const bool, int>(false, 2));
905 EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1));
908 TEST(PrintStlContainerTest, Set) {
909 const unsigned int a[] = { 3, 0, 5 };
910 set<unsigned int> set1(a, a + 3);
911 EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
914 TEST(PrintStlContainerTest, MultiSet) {
915 const int a[] = { 1, 1, 2, 5, 1 };
916 multiset<int> set1(a, a + 5);
917 EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
920 #if GTEST_HAS_STD_FORWARD_LIST_
922 TEST(PrintStlContainerTest, SinglyLinkedList) {
923 int a[] = { 9, 2, 8 };
924 const std::forward_list<int> ints(a, a + 3);
925 EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
927 #endif // GTEST_HAS_STD_FORWARD_LIST_
929 TEST(PrintStlContainerTest, Pair) {
930 pair<const bool, int> p(true, 5);
931 EXPECT_EQ("(true, 5)", Print(p));
934 TEST(PrintStlContainerTest, Vector) {
938 EXPECT_EQ("{ 1, 2 }", Print(v));
941 TEST(PrintStlContainerTest, LongSequence) {
942 const int a[100] = { 1, 2, 3 };
943 const vector<int> v(a, a + 100);
944 EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
945 "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v));
948 TEST(PrintStlContainerTest, NestedContainer) {
949 const int a1[] = { 1, 2 };
950 const int a2[] = { 3, 4, 5 };
951 const list<int> l1(a1, a1 + 2);
952 const list<int> l2(a2, a2 + 3);
954 vector<list<int> > v;
957 EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
960 TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
961 const int a[3] = { 1, 2, 3 };
962 NativeArray<int> b(a, 3, RelationToSourceReference());
963 EXPECT_EQ("{ 1, 2, 3 }", Print(b));
966 TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
967 const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
968 NativeArray<int[3]> b(a, 2, RelationToSourceReference());
969 EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
972 // Tests that a class named iterator isn't treated as a container.
978 TEST(PrintStlContainerTest, Iterator) {
980 EXPECT_EQ("1-byte object <00>", Print(it));
983 // Tests that a class named const_iterator isn't treated as a container.
985 struct const_iterator {
989 TEST(PrintStlContainerTest, ConstIterator) {
990 const_iterator it = {};
991 EXPECT_EQ("1-byte object <00>", Print(it));
994 #if GTEST_HAS_TR1_TUPLE
995 // Tests printing ::std::tr1::tuples.
997 // Tuples of various arities.
998 TEST(PrintTr1TupleTest, VariousSizes) {
999 ::std::tr1::tuple<> t0;
1000 EXPECT_EQ("()", Print(t0));
1002 ::std::tr1::tuple<int> t1(5);
1003 EXPECT_EQ("(5)", Print(t1));
1005 ::std::tr1::tuple<char, bool> t2('a', true);
1006 EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
1008 ::std::tr1::tuple<bool, int, int> t3(false, 2, 3);
1009 EXPECT_EQ("(false, 2, 3)", Print(t3));
1011 ::std::tr1::tuple<bool, int, int, int> t4(false, 2, 3, 4);
1012 EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
1014 ::std::tr1::tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true);
1015 EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5));
1017 ::std::tr1::tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6);
1018 EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6));
1020 ::std::tr1::tuple<bool, int, int, int, bool, int, int> t7(
1021 false, 2, 3, 4, true, 6, 7);
1022 EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7));
1024 ::std::tr1::tuple<bool, int, int, int, bool, int, int, bool> t8(
1025 false, 2, 3, 4, true, 6, 7, true);
1026 EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8));
1028 ::std::tr1::tuple<bool, int, int, int, bool, int, int, bool, int> t9(
1029 false, 2, 3, 4, true, 6, 7, true, 9);
1030 EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9));
1032 const char* const str = "8";
1033 // VC++ 2010's implementation of tuple of C++0x is deficient, requiring
1034 // an explicit type cast of NULL to be used.
1035 ::std::tr1::tuple<bool, char, short, testing::internal::Int32, // NOLINT
1036 testing::internal::Int64, float, double, const char*, void*,
1038 t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT
1039 ImplicitCast_<void*>(NULL), "10");
1040 EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
1041 " pointing to \"8\", NULL, \"10\")",
1046 TEST(PrintTr1TupleTest, NestedTuple) {
1047 ::std::tr1::tuple< ::std::tr1::tuple<int, bool>, char> nested(
1048 ::std::tr1::make_tuple(5, true), 'a');
1049 EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
1052 #endif // GTEST_HAS_TR1_TUPLE
1054 #if GTEST_HAS_STD_TUPLE_
1055 // Tests printing ::std::tuples.
1057 // Tuples of various arities.
1058 TEST(PrintStdTupleTest, VariousSizes) {
1060 EXPECT_EQ("()", Print(t0));
1062 ::std::tuple<int> t1(5);
1063 EXPECT_EQ("(5)", Print(t1));
1065 ::std::tuple<char, bool> t2('a', true);
1066 EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
1068 ::std::tuple<bool, int, int> t3(false, 2, 3);
1069 EXPECT_EQ("(false, 2, 3)", Print(t3));
1071 ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4);
1072 EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
1074 ::std::tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true);
1075 EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5));
1077 ::std::tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6);
1078 EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6));
1080 ::std::tuple<bool, int, int, int, bool, int, int> t7(
1081 false, 2, 3, 4, true, 6, 7);
1082 EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7));
1084 ::std::tuple<bool, int, int, int, bool, int, int, bool> t8(
1085 false, 2, 3, 4, true, 6, 7, true);
1086 EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8));
1088 ::std::tuple<bool, int, int, int, bool, int, int, bool, int> t9(
1089 false, 2, 3, 4, true, 6, 7, true, 9);
1090 EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9));
1092 const char* const str = "8";
1093 // VC++ 2010's implementation of tuple of C++0x is deficient, requiring
1094 // an explicit type cast of NULL to be used.
1095 ::std::tuple<bool, char, short, testing::internal::Int32, // NOLINT
1096 testing::internal::Int64, float, double, const char*, void*,
1098 t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT
1099 ImplicitCast_<void*>(NULL), "10");
1100 EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
1101 " pointing to \"8\", NULL, \"10\")",
1106 TEST(PrintStdTupleTest, NestedTuple) {
1107 ::std::tuple< ::std::tuple<int, bool>, char> nested(
1108 ::std::make_tuple(5, true), 'a');
1109 EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
1112 #endif // GTEST_LANG_CXX11
1114 #if GTEST_LANG_CXX11
1115 TEST(PrintNullptrT, Basic) {
1116 EXPECT_EQ("(nullptr)", Print(nullptr));
1118 #endif // GTEST_LANG_CXX11
1120 // Tests printing user-defined unprintable types.
1122 // Unprintable types in the global namespace.
1123 TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
1124 EXPECT_EQ("1-byte object <00>",
1125 Print(UnprintableTemplateInGlobal<char>()));
1128 // Unprintable types in a user namespace.
1129 TEST(PrintUnprintableTypeTest, InUserNamespace) {
1130 EXPECT_EQ("16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1131 Print(::foo::UnprintableInFoo()));
1134 // Unprintable types are that too big to be printed completely.
1137 Big() { memset(array, 0, sizeof(array)); }
1141 TEST(PrintUnpritableTypeTest, BigObject) {
1142 EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
1143 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1144 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1145 "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
1146 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1147 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1148 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
1152 // Tests printing user-defined streamable types.
1154 // Streamable types in the global namespace.
1155 TEST(PrintStreamableTypeTest, InGlobalNamespace) {
1156 StreamableInGlobal x;
1157 EXPECT_EQ("StreamableInGlobal", Print(x));
1158 EXPECT_EQ("StreamableInGlobal*", Print(&x));
1161 // Printable template types in a user namespace.
1162 TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
1163 EXPECT_EQ("StreamableTemplateInFoo: 0",
1164 Print(::foo::StreamableTemplateInFoo<int>()));
1167 // Tests printing a user-defined recursive container type that has a <<
1169 TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
1171 EXPECT_EQ("Streamable-PathLike", Print(x));
1172 const ::foo::PathLike cx;
1173 EXPECT_EQ("Streamable-PathLike", Print(cx));
1176 // Tests printing user-defined types that have a PrintTo() function.
1177 TEST(PrintPrintableTypeTest, InUserNamespace) {
1178 EXPECT_EQ("PrintableViaPrintTo: 0",
1179 Print(::foo::PrintableViaPrintTo()));
1182 // Tests printing a pointer to a user-defined type that has a <<
1183 // operator for its pointer.
1184 TEST(PrintPrintableTypeTest, PointerInUserNamespace) {
1185 ::foo::PointerPrintable x;
1186 EXPECT_EQ("PointerPrintable*", Print(&x));
1189 // Tests printing user-defined class template that have a PrintTo() function.
1190 TEST(PrintPrintableTypeTest, TemplateInUserNamespace) {
1191 EXPECT_EQ("PrintableViaPrintToTemplate: 5",
1192 Print(::foo::PrintableViaPrintToTemplate<int>(5)));
1195 // Tests that the universal printer prints both the address and the
1196 // value of a reference.
1197 TEST(PrintReferenceTest, PrintsAddressAndValue) {
1199 EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
1205 EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
1208 const ::foo::UnprintableInFoo x;
1209 EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object "
1210 "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1214 // Tests that the universal printer prints a function pointer passed by
1216 TEST(PrintReferenceTest, HandlesFunctionPointer) {
1217 void (*fp)(int n) = &MyFunction;
1218 const std::string fp_pointer_string =
1219 PrintPointer(reinterpret_cast<const void*>(&fp));
1220 // We cannot directly cast &MyFunction to const void* because the
1221 // standard disallows casting between pointers to functions and
1222 // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
1224 const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(
1225 reinterpret_cast<internal::BiggestInt>(fp)));
1226 EXPECT_EQ("@" + fp_pointer_string + " " + fp_string,
1230 // Tests that the universal printer prints a member function pointer
1231 // passed by reference.
1232 TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
1233 int (Foo::*p)(char ch) = &Foo::MyMethod;
1234 EXPECT_TRUE(HasPrefix(
1236 "@" + PrintPointer(reinterpret_cast<const void*>(&p)) + " " +
1237 Print(sizeof(p)) + "-byte object "));
1239 char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
1240 EXPECT_TRUE(HasPrefix(
1242 "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) + " " +
1243 Print(sizeof(p2)) + "-byte object "));
1246 // Tests that the universal printer prints a member variable pointer
1247 // passed by reference.
1248 TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
1249 int Foo::*p = &Foo::value; // NOLINT
1250 EXPECT_TRUE(HasPrefix(
1252 "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object "));
1255 // Tests that FormatForComparisonFailureMessage(), which is used to print
1256 // an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion
1257 // fails, formats the operand in the desired way.
1260 TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
1262 FormatForComparisonFailureMessage(123, 124).c_str());
1266 TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {
1268 EXPECT_EQ(PrintPointer(&n),
1269 FormatForComparisonFailureMessage(&n, &n).c_str());
1273 TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
1274 // In expression 'array == x', 'array' is compared by pointer.
1275 // Therefore we want to print an array operand as a pointer.
1276 int n[] = { 1, 2, 3 };
1277 EXPECT_EQ(PrintPointer(n),
1278 FormatForComparisonFailureMessage(n, n).c_str());
1281 // Tests formatting a char pointer when it's compared with another pointer.
1282 // In this case we want to print it as a raw pointer, as the comparison is by
1285 // char pointer vs pointer
1286 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
1287 // In expression 'p == x', where 'p' and 'x' are (const or not) char
1288 // pointers, the operands are compared by pointer. Therefore we
1289 // want to print 'p' as a pointer instead of a C string (we don't
1290 // even know if it's supposed to point to a valid C string).
1293 const char* s = "hello";
1294 EXPECT_EQ(PrintPointer(s),
1295 FormatForComparisonFailureMessage(s, s).c_str());
1299 EXPECT_EQ(PrintPointer(&ch),
1300 FormatForComparisonFailureMessage(&ch, &ch).c_str());
1303 // wchar_t pointer vs pointer
1304 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
1305 // In expression 'p == x', where 'p' and 'x' are (const or not) char
1306 // pointers, the operands are compared by pointer. Therefore we
1307 // want to print 'p' as a pointer instead of a wide C string (we don't
1308 // even know if it's supposed to point to a valid wide C string).
1311 const wchar_t* s = L"hello";
1312 EXPECT_EQ(PrintPointer(s),
1313 FormatForComparisonFailureMessage(s, s).c_str());
1317 EXPECT_EQ(PrintPointer(&ch),
1318 FormatForComparisonFailureMessage(&ch, &ch).c_str());
1321 // Tests formatting a char pointer when it's compared to a string object.
1322 // In this case we want to print the char pointer as a C string.
1324 #if GTEST_HAS_GLOBAL_STRING
1325 // char pointer vs ::string
1326 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsString) {
1327 const char* s = "hello \"world";
1328 EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped.
1329 FormatForComparisonFailureMessage(s, ::string()).c_str());
1332 char str[] = "hi\1";
1334 EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped.
1335 FormatForComparisonFailureMessage(p, ::string()).c_str());
1339 // char pointer vs std::string
1340 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) {
1341 const char* s = "hello \"world";
1342 EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped.
1343 FormatForComparisonFailureMessage(s, ::std::string()).c_str());
1346 char str[] = "hi\1";
1348 EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped.
1349 FormatForComparisonFailureMessage(p, ::std::string()).c_str());
1352 #if GTEST_HAS_GLOBAL_WSTRING
1353 // wchar_t pointer vs ::wstring
1354 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsWString) {
1355 const wchar_t* s = L"hi \"world";
1356 EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped.
1357 FormatForComparisonFailureMessage(s, ::wstring()).c_str());
1360 wchar_t str[] = L"hi\1";
1362 EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped.
1363 FormatForComparisonFailureMessage(p, ::wstring()).c_str());
1367 #if GTEST_HAS_STD_WSTRING
1368 // wchar_t pointer vs std::wstring
1369 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) {
1370 const wchar_t* s = L"hi \"world";
1371 EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped.
1372 FormatForComparisonFailureMessage(s, ::std::wstring()).c_str());
1375 wchar_t str[] = L"hi\1";
1377 EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped.
1378 FormatForComparisonFailureMessage(p, ::std::wstring()).c_str());
1382 // Tests formatting a char array when it's compared with a pointer or array.
1383 // In this case we want to print the array as a row pointer, as the comparison
1386 // char array vs pointer
1387 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) {
1388 char str[] = "hi \"world\"";
1390 EXPECT_EQ(PrintPointer(str),
1391 FormatForComparisonFailureMessage(str, p).c_str());
1394 // char array vs char array
1395 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) {
1396 const char str[] = "hi \"world\"";
1397 EXPECT_EQ(PrintPointer(str),
1398 FormatForComparisonFailureMessage(str, str).c_str());
1401 // wchar_t array vs pointer
1402 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) {
1403 wchar_t str[] = L"hi \"world\"";
1405 EXPECT_EQ(PrintPointer(str),
1406 FormatForComparisonFailureMessage(str, p).c_str());
1409 // wchar_t array vs wchar_t array
1410 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) {
1411 const wchar_t str[] = L"hi \"world\"";
1412 EXPECT_EQ(PrintPointer(str),
1413 FormatForComparisonFailureMessage(str, str).c_str());
1416 // Tests formatting a char array when it's compared with a string object.
1417 // In this case we want to print the array as a C string.
1419 #if GTEST_HAS_GLOBAL_STRING
1420 // char array vs string
1421 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsString) {
1422 const char str[] = "hi \"w\0rld\"";
1423 EXPECT_STREQ("\"hi \\\"w\"", // The content should be escaped.
1424 // Embedded NUL terminates the string.
1425 FormatForComparisonFailureMessage(str, ::string()).c_str());
1429 // char array vs std::string
1430 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) {
1431 const char str[] = "hi \"world\"";
1432 EXPECT_STREQ("\"hi \\\"world\\\"\"", // The content should be escaped.
1433 FormatForComparisonFailureMessage(str, ::std::string()).c_str());
1436 #if GTEST_HAS_GLOBAL_WSTRING
1437 // wchar_t array vs wstring
1438 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWString) {
1439 const wchar_t str[] = L"hi \"world\"";
1440 EXPECT_STREQ("L\"hi \\\"world\\\"\"", // The content should be escaped.
1441 FormatForComparisonFailureMessage(str, ::wstring()).c_str());
1445 #if GTEST_HAS_STD_WSTRING
1446 // wchar_t array vs std::wstring
1447 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
1448 const wchar_t str[] = L"hi \"w\0rld\"";
1450 "L\"hi \\\"w\"", // The content should be escaped.
1451 // Embedded NUL terminates the string.
1452 FormatForComparisonFailureMessage(str, ::std::wstring()).c_str());
1456 // Useful for testing PrintToString(). We cannot use EXPECT_EQ()
1457 // there as its implementation uses PrintToString(). The caller must
1458 // ensure that 'value' has no side effect.
1459 #define EXPECT_PRINT_TO_STRING_(value, expected_string) \
1460 EXPECT_TRUE(PrintToString(value) == (expected_string)) \
1461 << " where " #value " prints as " << (PrintToString(value))
1463 TEST(PrintToStringTest, WorksForScalar) {
1464 EXPECT_PRINT_TO_STRING_(123, "123");
1467 TEST(PrintToStringTest, WorksForPointerToConstChar) {
1468 const char* p = "hello";
1469 EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1472 TEST(PrintToStringTest, WorksForPointerToNonConstChar) {
1475 EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1478 TEST(PrintToStringTest, EscapesForPointerToConstChar) {
1479 const char* p = "hello\n";
1480 EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\"");
1483 TEST(PrintToStringTest, EscapesForPointerToNonConstChar) {
1484 char s[] = "hello\1";
1486 EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\"");
1489 TEST(PrintToStringTest, WorksForArray) {
1490 int n[3] = { 1, 2, 3 };
1491 EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }");
1494 TEST(PrintToStringTest, WorksForCharArray) {
1496 EXPECT_PRINT_TO_STRING_(s, "\"hello\"");
1499 TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {
1500 const char str_with_nul[] = "hello\0 world";
1501 EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\"");
1503 char mutable_str_with_nul[] = "hello\0 world";
1504 EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\"");
1507 TEST(PrintToStringTest, ContainsNonLatin) {
1508 // Sanity test with valid UTF-8. Prints both in hex and as text.
1509 std::string non_ascii_str = ::std::string("오전 4:30");
1510 EXPECT_PRINT_TO_STRING_(non_ascii_str,
1511 "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n"
1512 " As Text: \"오전 4:30\"");
1513 non_ascii_str = ::std::string("From ä — ẑ");
1514 EXPECT_PRINT_TO_STRING_(non_ascii_str,
1515 "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\""
1516 "\n As Text: \"From ä — ẑ\"");
1519 TEST(IsValidUTF8Test, IllFormedUTF8) {
1520 // The following test strings are ill-formed UTF-8 and are printed
1521 // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is
1522 // expected to fail, thus output does not contain "As Text:".
1524 static const char *const kTestdata[][2] = {
1525 // 2-byte lead byte followed by a single-byte character.
1526 {"\xC3\x74", "\"\\xC3t\""},
1527 // Valid 2-byte character followed by an orphan trail byte.
1528 {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""},
1529 // Lead byte without trail byte.
1530 {"abc\xC3", "\"abc\\xC3\""},
1531 // 3-byte lead byte, single-byte character, orphan trail byte.
1532 {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""},
1533 // Truncated 3-byte character.
1534 {"\xE2\x80", "\"\\xE2\\x80\""},
1535 // Truncated 3-byte character followed by valid 2-byte char.
1536 {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""},
1537 // Truncated 3-byte character followed by a single-byte character.
1538 {"\xE2\x80\x7A", "\"\\xE2\\x80z\""},
1539 // 3-byte lead byte followed by valid 3-byte character.
1540 {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""},
1541 // 4-byte lead byte followed by valid 3-byte character.
1542 {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""},
1543 // Truncated 4-byte character.
1544 {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""},
1545 // Invalid UTF-8 byte sequences embedded in other chars.
1546 {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""},
1547 {"abc\xC3\x84\xE2\x80\xC3\x84xyz",
1548 "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""},
1549 // Non-shortest UTF-8 byte sequences are also ill-formed.
1550 // The classics: xC0, xC1 lead byte.
1551 {"\xC0\x80", "\"\\xC0\\x80\""},
1552 {"\xC1\x81", "\"\\xC1\\x81\""},
1553 // Non-shortest sequences.
1554 {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
1555 {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
1556 // Last valid code point before surrogate range, should be printed as text,
1558 {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"\""},
1559 // Start of surrogate lead. Surrogates are not printed as text.
1560 {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""},
1561 // Last non-private surrogate lead.
1562 {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""},
1563 // First private-use surrogate lead.
1564 {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""},
1565 // Last private-use surrogate lead.
1566 {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
1567 // Mid-point of surrogate trail.
1568 {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
1569 // First valid code point after surrogate range, should be printed as text,
1571 {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""}
1574 for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) {
1575 EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
1579 #undef EXPECT_PRINT_TO_STRING_
1581 TEST(UniversalTersePrintTest, WorksForNonReference) {
1582 ::std::stringstream ss;
1583 UniversalTersePrint(123, &ss);
1584 EXPECT_EQ("123", ss.str());
1587 TEST(UniversalTersePrintTest, WorksForReference) {
1589 ::std::stringstream ss;
1590 UniversalTersePrint(n, &ss);
1591 EXPECT_EQ("123", ss.str());
1594 TEST(UniversalTersePrintTest, WorksForCString) {
1595 const char* s1 = "abc";
1596 ::std::stringstream ss1;
1597 UniversalTersePrint(s1, &ss1);
1598 EXPECT_EQ("\"abc\"", ss1.str());
1600 char* s2 = const_cast<char*>(s1);
1601 ::std::stringstream ss2;
1602 UniversalTersePrint(s2, &ss2);
1603 EXPECT_EQ("\"abc\"", ss2.str());
1605 const char* s3 = NULL;
1606 ::std::stringstream ss3;
1607 UniversalTersePrint(s3, &ss3);
1608 EXPECT_EQ("NULL", ss3.str());
1611 TEST(UniversalPrintTest, WorksForNonReference) {
1612 ::std::stringstream ss;
1613 UniversalPrint(123, &ss);
1614 EXPECT_EQ("123", ss.str());
1617 TEST(UniversalPrintTest, WorksForReference) {
1619 ::std::stringstream ss;
1620 UniversalPrint(n, &ss);
1621 EXPECT_EQ("123", ss.str());
1624 TEST(UniversalPrintTest, WorksForCString) {
1625 const char* s1 = "abc";
1626 ::std::stringstream ss1;
1627 UniversalPrint(s1, &ss1);
1628 EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str()));
1630 char* s2 = const_cast<char*>(s1);
1631 ::std::stringstream ss2;
1632 UniversalPrint(s2, &ss2);
1633 EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str()));
1635 const char* s3 = NULL;
1636 ::std::stringstream ss3;
1637 UniversalPrint(s3, &ss3);
1638 EXPECT_EQ("NULL", ss3.str());
1641 TEST(UniversalPrintTest, WorksForCharArray) {
1642 const char str[] = "\"Line\0 1\"\nLine 2";
1643 ::std::stringstream ss1;
1644 UniversalPrint(str, &ss1);
1645 EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str());
1647 const char mutable_str[] = "\"Line\0 1\"\nLine 2";
1648 ::std::stringstream ss2;
1649 UniversalPrint(mutable_str, &ss2);
1650 EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str());
1653 #if GTEST_HAS_TR1_TUPLE
1655 TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsEmptyTuple) {
1656 Strings result = UniversalTersePrintTupleFieldsToStrings(
1657 ::std::tr1::make_tuple());
1658 EXPECT_EQ(0u, result.size());
1661 TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsOneTuple) {
1662 Strings result = UniversalTersePrintTupleFieldsToStrings(
1663 ::std::tr1::make_tuple(1));
1664 ASSERT_EQ(1u, result.size());
1665 EXPECT_EQ("1", result[0]);
1668 TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTwoTuple) {
1669 Strings result = UniversalTersePrintTupleFieldsToStrings(
1670 ::std::tr1::make_tuple(1, 'a'));
1671 ASSERT_EQ(2u, result.size());
1672 EXPECT_EQ("1", result[0]);
1673 EXPECT_EQ("'a' (97, 0x61)", result[1]);
1676 TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTersely) {
1678 Strings result = UniversalTersePrintTupleFieldsToStrings(
1679 ::std::tr1::tuple<const int&, const char*>(n, "a"));
1680 ASSERT_EQ(2u, result.size());
1681 EXPECT_EQ("1", result[0]);
1682 EXPECT_EQ("\"a\"", result[1]);
1685 #endif // GTEST_HAS_TR1_TUPLE
1687 #if GTEST_HAS_STD_TUPLE_
1689 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
1690 Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
1691 EXPECT_EQ(0u, result.size());
1694 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
1695 Strings result = UniversalTersePrintTupleFieldsToStrings(
1696 ::std::make_tuple(1));
1697 ASSERT_EQ(1u, result.size());
1698 EXPECT_EQ("1", result[0]);
1701 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
1702 Strings result = UniversalTersePrintTupleFieldsToStrings(
1703 ::std::make_tuple(1, 'a'));
1704 ASSERT_EQ(2u, result.size());
1705 EXPECT_EQ("1", result[0]);
1706 EXPECT_EQ("'a' (97, 0x61)", result[1]);
1709 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
1711 Strings result = UniversalTersePrintTupleFieldsToStrings(
1712 ::std::tuple<const int&, const char*>(n, "a"));
1713 ASSERT_EQ(2u, result.size());
1714 EXPECT_EQ("1", result[0]);
1715 EXPECT_EQ("\"a\"", result[1]);
1718 #endif // GTEST_HAS_STD_TUPLE_
1722 TEST(PrintOptionalTest, Basic) {
1723 absl::optional<int> value;
1724 EXPECT_EQ("(nullopt)", PrintToString(value));
1726 EXPECT_EQ("(7)", PrintToString(value));
1727 EXPECT_EQ("(1.1)", PrintToString(absl::optional<double>{1.1}));
1728 EXPECT_EQ("(\"A\")", PrintToString(absl::optional<std::string>{"A"}));
1731 struct NonPrintable {
1732 unsigned char contents = 17;
1735 TEST(PrintOneofTest, Basic) {
1736 using Type = absl::variant<int, StreamableInGlobal, NonPrintable>;
1737 EXPECT_EQ("('int' with value 7)", PrintToString(Type(7)));
1738 EXPECT_EQ("('StreamableInGlobal' with value StreamableInGlobal)",
1739 PrintToString(Type(StreamableInGlobal{})));
1741 "('testing::gtest_printers_test::NonPrintable' with value 1-byte object "
1743 PrintToString(Type(NonPrintable{})));
1745 #endif // GTEST_HAS_ABSL
1747 } // namespace gtest_printers_test
1748 } // namespace testing