1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
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
13 // distribution.
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.
17 //
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.
29 
30 
31 // Google Test - The Google C++ Testing and Mocking Framework
32 //
33 // This file tests the universal value printer.
34 
35 #include <ctype.h>
36 #include <limits.h>
37 #include <string.h>
38 #include <algorithm>
39 #include <deque>
40 #include <forward_list>
41 #include <list>
42 #include <map>
43 #include <set>
44 #include <sstream>
45 #include <string>
46 #include <unordered_map>
47 #include <unordered_set>
48 #include <utility>
49 #include <vector>
50 
51 #include "gtest/gtest-printers.h"
52 #include "gtest/gtest.h"
53 
54 // Some user-defined types for testing the universal value printer.
55 
56 // An anonymous enum type.
57 enum AnonymousEnum {
58   kAE1 = -1,
59   kAE2 = 1
60 };
61 
62 // An enum without a user-defined printer.
63 enum EnumWithoutPrinter {
64   kEWP1 = -2,
65   kEWP2 = 42
66 };
67 
68 // An enum with a << operator.
69 enum EnumWithStreaming {
70   kEWS1 = 10
71 };
72 
operator <<(std::ostream & os,EnumWithStreaming e)73 std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
74   return os << (e == kEWS1 ? "kEWS1" : "invalid");
75 }
76 
77 // An enum with a PrintTo() function.
78 enum EnumWithPrintTo {
79   kEWPT1 = 1
80 };
81 
PrintTo(EnumWithPrintTo e,std::ostream * os)82 void PrintTo(EnumWithPrintTo e, std::ostream* os) {
83   *os << (e == kEWPT1 ? "kEWPT1" : "invalid");
84 }
85 
86 // A class implicitly convertible to BiggestInt.
87 class BiggestIntConvertible {
88  public:
operator ::testing::internal::BiggestInt() const89   operator ::testing::internal::BiggestInt() const { return 42; }
90 };
91 
92 // A user-defined unprintable class template in the global namespace.
93 template <typename T>
94 class UnprintableTemplateInGlobal {
95  public:
UnprintableTemplateInGlobal()96   UnprintableTemplateInGlobal() : value_() {}
97  private:
98   T value_;
99 };
100 
101 // A user-defined streamable type in the global namespace.
102 class StreamableInGlobal {
103  public:
~StreamableInGlobal()104   virtual ~StreamableInGlobal() {}
105 };
106 
operator <<(::std::ostream & os,const StreamableInGlobal &)107 inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) {
108   os << "StreamableInGlobal";
109 }
110 
operator <<(::std::ostream & os,const StreamableInGlobal *)111 void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) {
112   os << "StreamableInGlobal*";
113 }
114 
115 namespace foo {
116 
117 // A user-defined unprintable type in a user namespace.
118 class UnprintableInFoo {
119  public:
UnprintableInFoo()120   UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
z() const121   double z() const { return z_; }
122  private:
123   char xy_[8];
124   double z_;
125 };
126 
127 // A user-defined printable type in a user-chosen namespace.
128 struct PrintableViaPrintTo {
PrintableViaPrintTofoo::PrintableViaPrintTo129   PrintableViaPrintTo() : value() {}
130   int value;
131 };
132 
PrintTo(const PrintableViaPrintTo & x,::std::ostream * os)133 void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
134   *os << "PrintableViaPrintTo: " << x.value;
135 }
136 
137 // A type with a user-defined << for printing its pointer.
138 struct PointerPrintable {
139 };
140 
operator <<(::std::ostream & os,const PointerPrintable *)141 ::std::ostream& operator<<(::std::ostream& os,
142                            const PointerPrintable* /* x */) {
143   return os << "PointerPrintable*";
144 }
145 
146 // A user-defined printable class template in a user-chosen namespace.
147 template <typename T>
148 class PrintableViaPrintToTemplate {
149  public:
PrintableViaPrintToTemplate(const T & a_value)150   explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
151 
value() const152   const T& value() const { return value_; }
153  private:
154   T value_;
155 };
156 
157 template <typename T>
PrintTo(const PrintableViaPrintToTemplate<T> & x,::std::ostream * os)158 void PrintTo(const PrintableViaPrintToTemplate<T>& x, ::std::ostream* os) {
159   *os << "PrintableViaPrintToTemplate: " << x.value();
160 }
161 
162 // A user-defined streamable class template in a user namespace.
163 template <typename T>
164 class StreamableTemplateInFoo {
165  public:
StreamableTemplateInFoo()166   StreamableTemplateInFoo() : value_() {}
167 
value() const168   const T& value() const { return value_; }
169  private:
170   T value_;
171 };
172 
173 template <typename T>
operator <<(::std::ostream & os,const StreamableTemplateInFoo<T> & x)174 inline ::std::ostream& operator<<(::std::ostream& os,
175                                   const StreamableTemplateInFoo<T>& x) {
176   return os << "StreamableTemplateInFoo: " << x.value();
177 }
178 
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.
182 class PathLike {
183  public:
184   struct iterator {
185     typedef PathLike value_type;
186 
187     iterator& operator++();
188     PathLike& operator*();
189   };
190 
191   using value_type = char;
192   using const_iterator = iterator;
193 
PathLike()194   PathLike() {}
195 
begin() const196   iterator begin() const { return iterator(); }
end() const197   iterator end() const { return iterator(); }
198 
operator <<(::std::ostream & os,const PathLike &)199   friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) {
200     return os << "Streamable-PathLike";
201   }
202 };
203 
204 }  // namespace foo
205 
206 namespace testing {
207 namespace gtest_printers_test {
208 
209 using ::std::deque;
210 using ::std::list;
211 using ::std::make_pair;
212 using ::std::map;
213 using ::std::multimap;
214 using ::std::multiset;
215 using ::std::pair;
216 using ::std::set;
217 using ::std::vector;
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;
229 
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>
Print(const T & value)233 std::string Print(const T& value) {
234   ::std::stringstream ss;
235   UniversalPrinter<T>::Print(value, &ss);
236   return ss.str();
237 }
238 
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>
PrintByRef(const T & value)243 std::string PrintByRef(const T& value) {
244   ::std::stringstream ss;
245   UniversalPrinter<T&>::Print(value, &ss);
246   return ss.str();
247 }
248 
249 // Tests printing various enum types.
250 
TEST(PrintEnumTest,AnonymousEnum)251 TEST(PrintEnumTest, AnonymousEnum) {
252   EXPECT_EQ("-1", Print(kAE1));
253   EXPECT_EQ("1", Print(kAE2));
254 }
255 
TEST(PrintEnumTest,EnumWithoutPrinter)256 TEST(PrintEnumTest, EnumWithoutPrinter) {
257   EXPECT_EQ("-2", Print(kEWP1));
258   EXPECT_EQ("42", Print(kEWP2));
259 }
260 
TEST(PrintEnumTest,EnumWithStreaming)261 TEST(PrintEnumTest, EnumWithStreaming) {
262   EXPECT_EQ("kEWS1", Print(kEWS1));
263   EXPECT_EQ("invalid", Print(static_cast<EnumWithStreaming>(0)));
264 }
265 
TEST(PrintEnumTest,EnumWithPrintTo)266 TEST(PrintEnumTest, EnumWithPrintTo) {
267   EXPECT_EQ("kEWPT1", Print(kEWPT1));
268   EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0)));
269 }
270 
271 // Tests printing a class implicitly convertible to BiggestInt.
272 
TEST(PrintClassTest,BiggestIntConvertible)273 TEST(PrintClassTest, BiggestIntConvertible) {
274   EXPECT_EQ("42", Print(BiggestIntConvertible()));
275 }
276 
277 // Tests printing various char types.
278 
279 // char.
TEST(PrintCharTest,PlainChar)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'));
297 }
298 
299 // signed char.
TEST(PrintCharTest,SignedChar)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)));
304 }
305 
306 // unsigned char.
TEST(PrintCharTest,UnsignedChar)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')));
311 }
312 
313 // Tests printing other simple, built-in types.
314 
315 // bool.
TEST(PrintBuiltInTypeTest,Bool)316 TEST(PrintBuiltInTypeTest, Bool) {
317   EXPECT_EQ("false", Print(false));
318   EXPECT_EQ("true", Print(true));
319 }
320 
321 // wchar_t.
TEST(PrintBuiltInTypeTest,Wchar_t)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)));
341 }
342 
343 // Test that Int64 provides more storage than wchar_t.
TEST(PrintTypeSizeTest,Wchar_t)344 TEST(PrintTypeSizeTest, Wchar_t) {
345   EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64));
346 }
347 
348 // Various integer types.
TEST(PrintBuiltInTypeTest,Integer)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
360 }
361 
362 // Size types.
TEST(PrintBuiltInTypeTest,Size_t)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
369 }
370 
371 // Floating-points.
TEST(PrintBuiltInTypeTest,FloatingPoints)372 TEST(PrintBuiltInTypeTest, FloatingPoints) {
373   EXPECT_EQ("1.5", Print(1.5f));   // float
374   EXPECT_EQ("-2.5", Print(-2.5));  // double
375 }
376 
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.
PrintPointer(const void * p)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();
384 }
385 
386 // Tests printing C strings.
387 
388 // const char*.
TEST(PrintCStringTest,Const)389 TEST(PrintCStringTest, Const) {
390   const char* p = "World";
391   EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p));
392 }
393 
394 // char*.
TEST(PrintCStringTest,NonConst)395 TEST(PrintCStringTest, NonConst) {
396   char p[] = "Hi";
397   EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"",
398             Print(static_cast<char*>(p)));
399 }
400 
401 // NULL C string.
TEST(PrintCStringTest,Null)402 TEST(PrintCStringTest, Null) {
403   const char* p = nullptr;
404   EXPECT_EQ("NULL", Print(p));
405 }
406 
407 // Tests that C strings are escaped properly.
TEST(PrintCStringTest,EscapesProperly)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\"",
412             Print(p));
413 }
414 
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)
422 
423 // const wchar_t*.
TEST(PrintWideCStringTest,Const)424 TEST(PrintWideCStringTest, Const) {
425   const wchar_t* p = L"World";
426   EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p));
427 }
428 
429 // wchar_t*.
TEST(PrintWideCStringTest,NonConst)430 TEST(PrintWideCStringTest, NonConst) {
431   wchar_t p[] = L"Hi";
432   EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"",
433             Print(static_cast<wchar_t*>(p)));
434 }
435 
436 // NULL wide C string.
TEST(PrintWideCStringTest,Null)437 TEST(PrintWideCStringTest, Null) {
438   const wchar_t* p = nullptr;
439   EXPECT_EQ("NULL", Print(p));
440 }
441 
442 // Tests that wide C strings are escaped properly.
TEST(PrintWideCStringTest,EscapesProperly)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)));
449 }
450 #endif  // native wchar_t
451 
452 // Tests printing pointers to other char types.
453 
454 // signed char*.
TEST(PrintCharPointerTest,SignedChar)455 TEST(PrintCharPointerTest, SignedChar) {
456   signed char* p = reinterpret_cast<signed char*>(0x1234);
457   EXPECT_EQ(PrintPointer(p), Print(p));
458   p = nullptr;
459   EXPECT_EQ("NULL", Print(p));
460 }
461 
462 // const signed char*.
TEST(PrintCharPointerTest,ConstSignedChar)463 TEST(PrintCharPointerTest, ConstSignedChar) {
464   signed char* p = reinterpret_cast<signed char*>(0x1234);
465   EXPECT_EQ(PrintPointer(p), Print(p));
466   p = nullptr;
467   EXPECT_EQ("NULL", Print(p));
468 }
469 
470 // unsigned char*.
TEST(PrintCharPointerTest,UnsignedChar)471 TEST(PrintCharPointerTest, UnsignedChar) {
472   unsigned char* p = reinterpret_cast<unsigned char*>(0x1234);
473   EXPECT_EQ(PrintPointer(p), Print(p));
474   p = nullptr;
475   EXPECT_EQ("NULL", Print(p));
476 }
477 
478 // const unsigned char*.
TEST(PrintCharPointerTest,ConstUnsignedChar)479 TEST(PrintCharPointerTest, ConstUnsignedChar) {
480   const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234);
481   EXPECT_EQ(PrintPointer(p), Print(p));
482   p = nullptr;
483   EXPECT_EQ("NULL", Print(p));
484 }
485 
486 // Tests printing pointers to simple, built-in types.
487 
488 // bool*.
TEST(PrintPointerToBuiltInTypeTest,Bool)489 TEST(PrintPointerToBuiltInTypeTest, Bool) {
490   bool* p = reinterpret_cast<bool*>(0xABCD);
491   EXPECT_EQ(PrintPointer(p), Print(p));
492   p = nullptr;
493   EXPECT_EQ("NULL", Print(p));
494 }
495 
496 // void*.
TEST(PrintPointerToBuiltInTypeTest,Void)497 TEST(PrintPointerToBuiltInTypeTest, Void) {
498   void* p = reinterpret_cast<void*>(0xABCD);
499   EXPECT_EQ(PrintPointer(p), Print(p));
500   p = nullptr;
501   EXPECT_EQ("NULL", Print(p));
502 }
503 
504 // const void*.
TEST(PrintPointerToBuiltInTypeTest,ConstVoid)505 TEST(PrintPointerToBuiltInTypeTest, ConstVoid) {
506   const void* p = reinterpret_cast<const void*>(0xABCD);
507   EXPECT_EQ(PrintPointer(p), Print(p));
508   p = nullptr;
509   EXPECT_EQ("NULL", Print(p));
510 }
511 
512 // Tests printing pointers to pointers.
TEST(PrintPointerToPointerTest,IntPointerPointer)513 TEST(PrintPointerToPointerTest, IntPointerPointer) {
514   int** p = reinterpret_cast<int**>(0xABCD);
515   EXPECT_EQ(PrintPointer(p), Print(p));
516   p = nullptr;
517   EXPECT_EQ("NULL", Print(p));
518 }
519 
520 // Tests printing (non-member) function pointers.
521 
MyFunction(int)522 void MyFunction(int /* n */) {}
523 
TEST(PrintPointerTest,NonMemberFunctionPointer)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
528   // this limitation.
529   EXPECT_EQ(
530       PrintPointer(reinterpret_cast<const void*>(
531           reinterpret_cast<internal::BiggestInt>(&MyFunction))),
532       Print(&MyFunction));
533   int (*p)(bool) = NULL;  // NOLINT
534   EXPECT_EQ("NULL", Print(p));
535 }
536 
537 // An assertion predicate determining whether a one string is a prefix for
538 // another.
539 template <typename StringType>
HasPrefix(const StringType & str,const StringType & prefix)540 AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
541   if (str.find(prefix, 0) == 0)
542     return AssertionSuccess();
543 
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";
549 }
550 
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.
555 
556 struct Foo {
557  public:
~Footesting::gtest_printers_test::Foo558   virtual ~Foo() {}
MyMethodtesting::gtest_printers_test::Foo559   int MyMethod(char x) { return x + 1; }
MyVirtualMethodtesting::gtest_printers_test::Foo560   virtual char MyVirtualMethod(int /* n */) { return 'a'; }
561 
562   int value;
563 };
564 
TEST(PrintPointerTest,MemberVariablePointer)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 "));
571 }
572 
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.
TEST(PrintPointerTest,MemberFunctionPointer)577 TEST(PrintPointerTest, MemberFunctionPointer) {
578   EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod),
579                         Print(sizeof(&Foo::MyMethod)) + "-byte object "));
580   EXPECT_TRUE(
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 "));
586 }
587 
588 // Tests printing C arrays.
589 
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>
PrintArrayHelper(T (& a)[N])593 std::string PrintArrayHelper(T (&a)[N]) {
594   return Print(a);
595 }
596 
597 // One-dimensional array.
TEST(PrintArrayTest,OneDimensionalArray)598 TEST(PrintArrayTest, OneDimensionalArray) {
599   int a[5] = { 1, 2, 3, 4, 5 };
600   EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
601 }
602 
603 // Two-dimensional array.
TEST(PrintArrayTest,TwoDimensionalArray)604 TEST(PrintArrayTest, TwoDimensionalArray) {
605   int a[2][5] = {
606     { 1, 2, 3, 4, 5 },
607     { 6, 7, 8, 9, 0 }
608   };
609   EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
610 }
611 
612 // Array of const elements.
TEST(PrintArrayTest,ConstArray)613 TEST(PrintArrayTest, ConstArray) {
614   const bool a[1] = { false };
615   EXPECT_EQ("{ false }", PrintArrayHelper(a));
616 }
617 
618 // char array without terminating NUL.
TEST(PrintArrayTest,CharArrayWithNoTerminatingNul)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));
623 }
624 
625 // const char array with terminating NUL.
TEST(PrintArrayTest,ConstCharArrayWithTerminatingNul)626 TEST(PrintArrayTest, ConstCharArrayWithTerminatingNul) {
627   const char a[] = "\0Hi";
628   EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a));
629 }
630 
631 // const wchar_t array without terminating NUL.
TEST(PrintArrayTest,WCharArrayWithNoTerminatingNul)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));
636 }
637 
638 // wchar_t array with terminating NUL.
TEST(PrintArrayTest,WConstCharArrayWithTerminatingNul)639 TEST(PrintArrayTest, WConstCharArrayWithTerminatingNul) {
640   const wchar_t a[] = L"\0Hi";
641   EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a));
642 }
643 
644 // Array of objects.
TEST(PrintArrayTest,ObjectArray)645 TEST(PrintArrayTest, ObjectArray) {
646   std::string a[3] = {"Hi", "Hello", "Ni hao"};
647   EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a));
648 }
649 
650 // Array with many elements.
TEST(PrintArrayTest,BigArray)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));
655 }
656 
657 // Tests printing ::string and ::std::string.
658 
659 #if GTEST_HAS_GLOBAL_STRING
660 // ::string.
TEST(PrintStringTest,StringInGlobalNamespace)661 TEST(PrintStringTest, StringInGlobalNamespace) {
662   const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
663   const ::string str(s, sizeof(s));
664   EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
665             Print(str));
666 }
667 #endif  // GTEST_HAS_GLOBAL_STRING
668 
669 // ::std::string.
TEST(PrintStringTest,StringInStdNamespace)670 TEST(PrintStringTest, StringInStdNamespace) {
671   const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
672   const ::std::string str(s, sizeof(s));
673   EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
674             Print(str));
675 }
676 
TEST(PrintStringTest,StringAmbiguousHex)677 TEST(PrintStringTest, StringAmbiguousHex) {
678   // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of:
679   // '\x6', '\x6B', or '\x6BA'.
680 
681   // a hex escaping sequence following by a decimal digit
682   EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3")));
683   // a hex escaping sequence following by a hex digit (lower-case)
684   EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas")));
685   // a hex escaping sequence following by a hex digit (upper-case)
686   EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA")));
687   // a hex escaping sequence following by a non-xdigit
688   EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
689 }
690 
691 // Tests printing ::wstring and ::std::wstring.
692 
693 #if GTEST_HAS_GLOBAL_WSTRING
694 // ::wstring.
TEST(PrintWideStringTest,StringInGlobalNamespace)695 TEST(PrintWideStringTest, StringInGlobalNamespace) {
696   const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
697   const ::wstring str(s, sizeof(s)/sizeof(wchar_t));
698   EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
699             "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
700             Print(str));
701 }
702 #endif  // GTEST_HAS_GLOBAL_WSTRING
703 
704 #if GTEST_HAS_STD_WSTRING
705 // ::std::wstring.
TEST(PrintWideStringTest,StringInStdNamespace)706 TEST(PrintWideStringTest, StringInStdNamespace) {
707   const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
708   const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t));
709   EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
710             "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
711             Print(str));
712 }
713 
TEST(PrintWideStringTest,StringAmbiguousHex)714 TEST(PrintWideStringTest, StringAmbiguousHex) {
715   // same for wide strings.
716   EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3")));
717   EXPECT_EQ("L\"mm\\x6\" L\"bananas\"",
718             Print(::std::wstring(L"mm\x6" L"bananas")));
719   EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"",
720             Print(::std::wstring(L"NOM\x6" L"BANANA")));
721   EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
722 }
723 #endif  // GTEST_HAS_STD_WSTRING
724 
725 // Tests printing types that support generic streaming (i.e. streaming
726 // to std::basic_ostream<Char, CharTraits> for any valid Char and
727 // CharTraits types).
728 
729 // Tests printing a non-template type that supports generic streaming.
730 
731 class AllowsGenericStreaming {};
732 
733 template <typename Char, typename CharTraits>
operator <<(std::basic_ostream<Char,CharTraits> & os,const AllowsGenericStreaming &)734 std::basic_ostream<Char, CharTraits>& operator<<(
735     std::basic_ostream<Char, CharTraits>& os,
736     const AllowsGenericStreaming& /* a */) {
737   return os << "AllowsGenericStreaming";
738 }
739 
TEST(PrintTypeWithGenericStreamingTest,NonTemplateType)740 TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) {
741   AllowsGenericStreaming a;
742   EXPECT_EQ("AllowsGenericStreaming", Print(a));
743 }
744 
745 // Tests printing a template type that supports generic streaming.
746 
747 template <typename T>
748 class AllowsGenericStreamingTemplate {};
749 
750 template <typename Char, typename CharTraits, typename T>
operator <<(std::basic_ostream<Char,CharTraits> & os,const AllowsGenericStreamingTemplate<T> &)751 std::basic_ostream<Char, CharTraits>& operator<<(
752     std::basic_ostream<Char, CharTraits>& os,
753     const AllowsGenericStreamingTemplate<T>& /* a */) {
754   return os << "AllowsGenericStreamingTemplate";
755 }
756 
TEST(PrintTypeWithGenericStreamingTest,TemplateType)757 TEST(PrintTypeWithGenericStreamingTest, TemplateType) {
758   AllowsGenericStreamingTemplate<int> a;
759   EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a));
760 }
761 
762 // Tests printing a type that supports generic streaming and can be
763 // implicitly converted to another printable type.
764 
765 template <typename T>
766 class AllowsGenericStreamingAndImplicitConversionTemplate {
767  public:
operator bool() const768   operator bool() const { return false; }
769 };
770 
771 template <typename Char, typename CharTraits, typename T>
operator <<(std::basic_ostream<Char,CharTraits> & os,const AllowsGenericStreamingAndImplicitConversionTemplate<T> &)772 std::basic_ostream<Char, CharTraits>& operator<<(
773     std::basic_ostream<Char, CharTraits>& os,
774     const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) {
775   return os << "AllowsGenericStreamingAndImplicitConversionTemplate";
776 }
777 
TEST(PrintTypeWithGenericStreamingTest,TypeImplicitlyConvertible)778 TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
779   AllowsGenericStreamingAndImplicitConversionTemplate<int> a;
780   EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
781 }
782 
783 #if GTEST_HAS_ABSL
784 
785 // Tests printing ::absl::string_view.
786 
TEST(PrintStringViewTest,SimpleStringView)787 TEST(PrintStringViewTest, SimpleStringView) {
788   const ::absl::string_view sp = "Hello";
789   EXPECT_EQ("\"Hello\"", Print(sp));
790 }
791 
TEST(PrintStringViewTest,UnprintableCharacters)792 TEST(PrintStringViewTest, UnprintableCharacters) {
793   const char str[] = "NUL (\0) and \r\t";
794   const ::absl::string_view sp(str, sizeof(str) - 1);
795   EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
796 }
797 
798 #endif  // GTEST_HAS_ABSL
799 
800 // Tests printing STL containers.
801 
TEST(PrintStlContainerTest,EmptyDeque)802 TEST(PrintStlContainerTest, EmptyDeque) {
803   deque<char> empty;
804   EXPECT_EQ("{}", Print(empty));
805 }
806 
TEST(PrintStlContainerTest,NonEmptyDeque)807 TEST(PrintStlContainerTest, NonEmptyDeque) {
808   deque<int> non_empty;
809   non_empty.push_back(1);
810   non_empty.push_back(3);
811   EXPECT_EQ("{ 1, 3 }", Print(non_empty));
812 }
813 
814 
TEST(PrintStlContainerTest,OneElementHashMap)815 TEST(PrintStlContainerTest, OneElementHashMap) {
816   ::std::unordered_map<int, char> map1;
817   map1[1] = 'a';
818   EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1));
819 }
820 
TEST(PrintStlContainerTest,HashMultiMap)821 TEST(PrintStlContainerTest, HashMultiMap) {
822   ::std::unordered_multimap<int, bool> map1;
823   map1.insert(make_pair(5, true));
824   map1.insert(make_pair(5, false));
825 
826   // Elements of hash_multimap can be printed in any order.
827   const std::string result = Print(map1);
828   EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
829               result == "{ (5, false), (5, true) }")
830                   << " where Print(map1) returns \"" << result << "\".";
831 }
832 
833 
834 
TEST(PrintStlContainerTest,HashSet)835 TEST(PrintStlContainerTest, HashSet) {
836   ::std::unordered_set<int> set1;
837   set1.insert(1);
838   EXPECT_EQ("{ 1 }", Print(set1));
839 }
840 
TEST(PrintStlContainerTest,HashMultiSet)841 TEST(PrintStlContainerTest, HashMultiSet) {
842   const int kSize = 5;
843   int a[kSize] = { 1, 1, 2, 5, 1 };
844   ::std::unordered_multiset<int> set1(a, a + kSize);
845 
846   // Elements of hash_multiset can be printed in any order.
847   const std::string result = Print(set1);
848   const std::string expected_pattern = "{ d, d, d, d, d }";  // d means a digit.
849 
850   // Verifies the result matches the expected pattern; also extracts
851   // the numbers in the result.
852   ASSERT_EQ(expected_pattern.length(), result.length());
853   std::vector<int> numbers;
854   for (size_t i = 0; i != result.length(); i++) {
855     if (expected_pattern[i] == 'd') {
856       ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
857       numbers.push_back(result[i] - '0');
858     } else {
859       EXPECT_EQ(expected_pattern[i], result[i]) << " where result is "
860                                                 << result;
861     }
862   }
863 
864   // Makes sure the result contains the right numbers.
865   std::sort(numbers.begin(), numbers.end());
866   std::sort(a, a + kSize);
867   EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
868 }
869 
870 
TEST(PrintStlContainerTest,List)871 TEST(PrintStlContainerTest, List) {
872   const std::string a[] = {"hello", "world"};
873   const list<std::string> strings(a, a + 2);
874   EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings));
875 }
876 
TEST(PrintStlContainerTest,Map)877 TEST(PrintStlContainerTest, Map) {
878   map<int, bool> map1;
879   map1[1] = true;
880   map1[5] = false;
881   map1[3] = true;
882   EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1));
883 }
884 
TEST(PrintStlContainerTest,MultiMap)885 TEST(PrintStlContainerTest, MultiMap) {
886   multimap<bool, int> map1;
887   // The make_pair template function would deduce the type as
888   // pair<bool, int> here, and since the key part in a multimap has to
889   // be constant, without a templated ctor in the pair class (as in
890   // libCstd on Solaris), make_pair call would fail to compile as no
891   // implicit conversion is found.  Thus explicit typename is used
892   // here instead.
893   map1.insert(pair<const bool, int>(true, 0));
894   map1.insert(pair<const bool, int>(true, 1));
895   map1.insert(pair<const bool, int>(false, 2));
896   EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1));
897 }
898 
TEST(PrintStlContainerTest,Set)899 TEST(PrintStlContainerTest, Set) {
900   const unsigned int a[] = { 3, 0, 5 };
901   set<unsigned int> set1(a, a + 3);
902   EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
903 }
904 
TEST(PrintStlContainerTest,MultiSet)905 TEST(PrintStlContainerTest, MultiSet) {
906   const int a[] = { 1, 1, 2, 5, 1 };
907   multiset<int> set1(a, a + 5);
908   EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
909 }
910 
911 
TEST(PrintStlContainerTest,SinglyLinkedList)912 TEST(PrintStlContainerTest, SinglyLinkedList) {
913   int a[] = { 9, 2, 8 };
914   const std::forward_list<int> ints(a, a + 3);
915   EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
916 }
917 
TEST(PrintStlContainerTest,Pair)918 TEST(PrintStlContainerTest, Pair) {
919   pair<const bool, int> p(true, 5);
920   EXPECT_EQ("(true, 5)", Print(p));
921 }
922 
TEST(PrintStlContainerTest,Vector)923 TEST(PrintStlContainerTest, Vector) {
924   vector<int> v;
925   v.push_back(1);
926   v.push_back(2);
927   EXPECT_EQ("{ 1, 2 }", Print(v));
928 }
929 
TEST(PrintStlContainerTest,LongSequence)930 TEST(PrintStlContainerTest, LongSequence) {
931   const int a[100] = { 1, 2, 3 };
932   const vector<int> v(a, a + 100);
933   EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
934             "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v));
935 }
936 
TEST(PrintStlContainerTest,NestedContainer)937 TEST(PrintStlContainerTest, NestedContainer) {
938   const int a1[] = { 1, 2 };
939   const int a2[] = { 3, 4, 5 };
940   const list<int> l1(a1, a1 + 2);
941   const list<int> l2(a2, a2 + 3);
942 
943   vector<list<int> > v;
944   v.push_back(l1);
945   v.push_back(l2);
946   EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
947 }
948 
TEST(PrintStlContainerTest,OneDimensionalNativeArray)949 TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
950   const int a[3] = { 1, 2, 3 };
951   NativeArray<int> b(a, 3, RelationToSourceReference());
952   EXPECT_EQ("{ 1, 2, 3 }", Print(b));
953 }
954 
TEST(PrintStlContainerTest,TwoDimensionalNativeArray)955 TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
956   const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
957   NativeArray<int[3]> b(a, 2, RelationToSourceReference());
958   EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
959 }
960 
961 // Tests that a class named iterator isn't treated as a container.
962 
963 struct iterator {
964   char x;
965 };
966 
TEST(PrintStlContainerTest,Iterator)967 TEST(PrintStlContainerTest, Iterator) {
968   iterator it = {};
969   EXPECT_EQ("1-byte object <00>", Print(it));
970 }
971 
972 // Tests that a class named const_iterator isn't treated as a container.
973 
974 struct const_iterator {
975   char x;
976 };
977 
TEST(PrintStlContainerTest,ConstIterator)978 TEST(PrintStlContainerTest, ConstIterator) {
979   const_iterator it = {};
980   EXPECT_EQ("1-byte object <00>", Print(it));
981 }
982 
983 // Tests printing ::std::tuples.
984 
985 // Tuples of various arities.
TEST(PrintStdTupleTest,VariousSizes)986 TEST(PrintStdTupleTest, VariousSizes) {
987   ::std::tuple<> t0;
988   EXPECT_EQ("()", Print(t0));
989 
990   ::std::tuple<int> t1(5);
991   EXPECT_EQ("(5)", Print(t1));
992 
993   ::std::tuple<char, bool> t2('a', true);
994   EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
995 
996   ::std::tuple<bool, int, int> t3(false, 2, 3);
997   EXPECT_EQ("(false, 2, 3)", Print(t3));
998 
999   ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4);
1000   EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
1001 
1002   const char* const str = "8";
1003   ::std::tuple<bool, char, short, testing::internal::Int32,  // NOLINT
1004                testing::internal::Int64, float, double, const char*, void*,
1005                std::string>
1006       t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str,  // NOLINT
1007           nullptr, "10");
1008   EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
1009             " pointing to \"8\", NULL, \"10\")",
1010             Print(t10));
1011 }
1012 
1013 // Nested tuples.
TEST(PrintStdTupleTest,NestedTuple)1014 TEST(PrintStdTupleTest, NestedTuple) {
1015   ::std::tuple< ::std::tuple<int, bool>, char> nested(
1016       ::std::make_tuple(5, true), 'a');
1017   EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
1018 }
1019 
TEST(PrintNullptrT,Basic)1020 TEST(PrintNullptrT, Basic) {
1021   EXPECT_EQ("(nullptr)", Print(nullptr));
1022 }
1023 
TEST(PrintReferenceWrapper,Printable)1024 TEST(PrintReferenceWrapper, Printable) {
1025   int x = 5;
1026   EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::ref(x)));
1027   EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::cref(x)));
1028 }
1029 
TEST(PrintReferenceWrapper,Unprintable)1030 TEST(PrintReferenceWrapper, Unprintable) {
1031   ::foo::UnprintableInFoo up;
1032   EXPECT_EQ(
1033       "@" + PrintPointer(&up) +
1034           " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1035       Print(std::ref(up)));
1036   EXPECT_EQ(
1037       "@" + PrintPointer(&up) +
1038           " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1039       Print(std::cref(up)));
1040 }
1041 
1042 // Tests printing user-defined unprintable types.
1043 
1044 // Unprintable types in the global namespace.
TEST(PrintUnprintableTypeTest,InGlobalNamespace)1045 TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
1046   EXPECT_EQ("1-byte object <00>",
1047             Print(UnprintableTemplateInGlobal<char>()));
1048 }
1049 
1050 // Unprintable types in a user namespace.
TEST(PrintUnprintableTypeTest,InUserNamespace)1051 TEST(PrintUnprintableTypeTest, InUserNamespace) {
1052   EXPECT_EQ("16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1053             Print(::foo::UnprintableInFoo()));
1054 }
1055 
1056 // Unprintable types are that too big to be printed completely.
1057 
1058 struct Big {
Bigtesting::gtest_printers_test::Big1059   Big() { memset(array, 0, sizeof(array)); }
1060   char array[257];
1061 };
1062 
TEST(PrintUnpritableTypeTest,BigObject)1063 TEST(PrintUnpritableTypeTest, BigObject) {
1064   EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
1065             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1066             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1067             "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
1068             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1069             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1070             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
1071             Print(Big()));
1072 }
1073 
1074 // Tests printing user-defined streamable types.
1075 
1076 // Streamable types in the global namespace.
TEST(PrintStreamableTypeTest,InGlobalNamespace)1077 TEST(PrintStreamableTypeTest, InGlobalNamespace) {
1078   StreamableInGlobal x;
1079   EXPECT_EQ("StreamableInGlobal", Print(x));
1080   EXPECT_EQ("StreamableInGlobal*", Print(&x));
1081 }
1082 
1083 // Printable template types in a user namespace.
TEST(PrintStreamableTypeTest,TemplateTypeInUserNamespace)1084 TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
1085   EXPECT_EQ("StreamableTemplateInFoo: 0",
1086             Print(::foo::StreamableTemplateInFoo<int>()));
1087 }
1088 
1089 // Tests printing a user-defined recursive container type that has a <<
1090 // operator.
TEST(PrintStreamableTypeTest,PathLikeInUserNamespace)1091 TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
1092   ::foo::PathLike x;
1093   EXPECT_EQ("Streamable-PathLike", Print(x));
1094   const ::foo::PathLike cx;
1095   EXPECT_EQ("Streamable-PathLike", Print(cx));
1096 }
1097 
1098 // Tests printing user-defined types that have a PrintTo() function.
TEST(PrintPrintableTypeTest,InUserNamespace)1099 TEST(PrintPrintableTypeTest, InUserNamespace) {
1100   EXPECT_EQ("PrintableViaPrintTo: 0",
1101             Print(::foo::PrintableViaPrintTo()));
1102 }
1103 
1104 // Tests printing a pointer to a user-defined type that has a <<
1105 // operator for its pointer.
TEST(PrintPrintableTypeTest,PointerInUserNamespace)1106 TEST(PrintPrintableTypeTest, PointerInUserNamespace) {
1107   ::foo::PointerPrintable x;
1108   EXPECT_EQ("PointerPrintable*", Print(&x));
1109 }
1110 
1111 // Tests printing user-defined class template that have a PrintTo() function.
TEST(PrintPrintableTypeTest,TemplateInUserNamespace)1112 TEST(PrintPrintableTypeTest, TemplateInUserNamespace) {
1113   EXPECT_EQ("PrintableViaPrintToTemplate: 5",
1114             Print(::foo::PrintableViaPrintToTemplate<int>(5)));
1115 }
1116 
1117 // Tests that the universal printer prints both the address and the
1118 // value of a reference.
TEST(PrintReferenceTest,PrintsAddressAndValue)1119 TEST(PrintReferenceTest, PrintsAddressAndValue) {
1120   int n = 5;
1121   EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
1122 
1123   int a[2][3] = {
1124     { 0, 1, 2 },
1125     { 3, 4, 5 }
1126   };
1127   EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
1128             PrintByRef(a));
1129 
1130   const ::foo::UnprintableInFoo x;
1131   EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object "
1132             "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1133             PrintByRef(x));
1134 }
1135 
1136 // Tests that the universal printer prints a function pointer passed by
1137 // reference.
TEST(PrintReferenceTest,HandlesFunctionPointer)1138 TEST(PrintReferenceTest, HandlesFunctionPointer) {
1139   void (*fp)(int n) = &MyFunction;
1140   const std::string fp_pointer_string =
1141       PrintPointer(reinterpret_cast<const void*>(&fp));
1142   // We cannot directly cast &MyFunction to const void* because the
1143   // standard disallows casting between pointers to functions and
1144   // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
1145   // this limitation.
1146   const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(
1147       reinterpret_cast<internal::BiggestInt>(fp)));
1148   EXPECT_EQ("@" + fp_pointer_string + " " + fp_string,
1149             PrintByRef(fp));
1150 }
1151 
1152 // Tests that the universal printer prints a member function pointer
1153 // passed by reference.
TEST(PrintReferenceTest,HandlesMemberFunctionPointer)1154 TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
1155   int (Foo::*p)(char ch) = &Foo::MyMethod;
1156   EXPECT_TRUE(HasPrefix(
1157       PrintByRef(p),
1158       "@" + PrintPointer(reinterpret_cast<const void*>(&p)) + " " +
1159           Print(sizeof(p)) + "-byte object "));
1160 
1161   char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
1162   EXPECT_TRUE(HasPrefix(
1163       PrintByRef(p2),
1164       "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) + " " +
1165           Print(sizeof(p2)) + "-byte object "));
1166 }
1167 
1168 // Tests that the universal printer prints a member variable pointer
1169 // passed by reference.
TEST(PrintReferenceTest,HandlesMemberVariablePointer)1170 TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
1171   int Foo::*p = &Foo::value;  // NOLINT
1172   EXPECT_TRUE(HasPrefix(
1173       PrintByRef(p),
1174       "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object "));
1175 }
1176 
1177 // Tests that FormatForComparisonFailureMessage(), which is used to print
1178 // an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion
1179 // fails, formats the operand in the desired way.
1180 
1181 // scalar
TEST(FormatForComparisonFailureMessageTest,WorksForScalar)1182 TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
1183   EXPECT_STREQ("123",
1184                FormatForComparisonFailureMessage(123, 124).c_str());
1185 }
1186 
1187 // non-char pointer
TEST(FormatForComparisonFailureMessageTest,WorksForNonCharPointer)1188 TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {
1189   int n = 0;
1190   EXPECT_EQ(PrintPointer(&n),
1191             FormatForComparisonFailureMessage(&n, &n).c_str());
1192 }
1193 
1194 // non-char array
TEST(FormatForComparisonFailureMessageTest,FormatsNonCharArrayAsPointer)1195 TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
1196   // In expression 'array == x', 'array' is compared by pointer.
1197   // Therefore we want to print an array operand as a pointer.
1198   int n[] = { 1, 2, 3 };
1199   EXPECT_EQ(PrintPointer(n),
1200             FormatForComparisonFailureMessage(n, n).c_str());
1201 }
1202 
1203 // Tests formatting a char pointer when it's compared with another pointer.
1204 // In this case we want to print it as a raw pointer, as the comparison is by
1205 // pointer.
1206 
1207 // char pointer vs pointer
TEST(FormatForComparisonFailureMessageTest,WorksForCharPointerVsPointer)1208 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
1209   // In expression 'p == x', where 'p' and 'x' are (const or not) char
1210   // pointers, the operands are compared by pointer.  Therefore we
1211   // want to print 'p' as a pointer instead of a C string (we don't
1212   // even know if it's supposed to point to a valid C string).
1213 
1214   // const char*
1215   const char* s = "hello";
1216   EXPECT_EQ(PrintPointer(s),
1217             FormatForComparisonFailureMessage(s, s).c_str());
1218 
1219   // char*
1220   char ch = 'a';
1221   EXPECT_EQ(PrintPointer(&ch),
1222             FormatForComparisonFailureMessage(&ch, &ch).c_str());
1223 }
1224 
1225 // wchar_t pointer vs pointer
TEST(FormatForComparisonFailureMessageTest,WorksForWCharPointerVsPointer)1226 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
1227   // In expression 'p == x', where 'p' and 'x' are (const or not) char
1228   // pointers, the operands are compared by pointer.  Therefore we
1229   // want to print 'p' as a pointer instead of a wide C string (we don't
1230   // even know if it's supposed to point to a valid wide C string).
1231 
1232   // const wchar_t*
1233   const wchar_t* s = L"hello";
1234   EXPECT_EQ(PrintPointer(s),
1235             FormatForComparisonFailureMessage(s, s).c_str());
1236 
1237   // wchar_t*
1238   wchar_t ch = L'a';
1239   EXPECT_EQ(PrintPointer(&ch),
1240             FormatForComparisonFailureMessage(&ch, &ch).c_str());
1241 }
1242 
1243 // Tests formatting a char pointer when it's compared to a string object.
1244 // In this case we want to print the char pointer as a C string.
1245 
1246 #if GTEST_HAS_GLOBAL_STRING
1247 // char pointer vs ::string
TEST(FormatForComparisonFailureMessageTest,WorksForCharPointerVsString)1248 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsString) {
1249   const char* s = "hello \"world";
1250   EXPECT_STREQ("\"hello \\\"world\"",  // The string content should be escaped.
1251                FormatForComparisonFailureMessage(s, ::string()).c_str());
1252 
1253   // char*
1254   char str[] = "hi\1";
1255   char* p = str;
1256   EXPECT_STREQ("\"hi\\x1\"",  // The string content should be escaped.
1257                FormatForComparisonFailureMessage(p, ::string()).c_str());
1258 }
1259 #endif
1260 
1261 // char pointer vs std::string
TEST(FormatForComparisonFailureMessageTest,WorksForCharPointerVsStdString)1262 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) {
1263   const char* s = "hello \"world";
1264   EXPECT_STREQ("\"hello \\\"world\"",  // The string content should be escaped.
1265                FormatForComparisonFailureMessage(s, ::std::string()).c_str());
1266 
1267   // char*
1268   char str[] = "hi\1";
1269   char* p = str;
1270   EXPECT_STREQ("\"hi\\x1\"",  // The string content should be escaped.
1271                FormatForComparisonFailureMessage(p, ::std::string()).c_str());
1272 }
1273 
1274 #if GTEST_HAS_GLOBAL_WSTRING
1275 // wchar_t pointer vs ::wstring
TEST(FormatForComparisonFailureMessageTest,WorksForWCharPointerVsWString)1276 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsWString) {
1277   const wchar_t* s = L"hi \"world";
1278   EXPECT_STREQ("L\"hi \\\"world\"",  // The string content should be escaped.
1279                FormatForComparisonFailureMessage(s, ::wstring()).c_str());
1280 
1281   // wchar_t*
1282   wchar_t str[] = L"hi\1";
1283   wchar_t* p = str;
1284   EXPECT_STREQ("L\"hi\\x1\"",  // The string content should be escaped.
1285                FormatForComparisonFailureMessage(p, ::wstring()).c_str());
1286 }
1287 #endif
1288 
1289 #if GTEST_HAS_STD_WSTRING
1290 // wchar_t pointer vs std::wstring
TEST(FormatForComparisonFailureMessageTest,WorksForWCharPointerVsStdWString)1291 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) {
1292   const wchar_t* s = L"hi \"world";
1293   EXPECT_STREQ("L\"hi \\\"world\"",  // The string content should be escaped.
1294                FormatForComparisonFailureMessage(s, ::std::wstring()).c_str());
1295 
1296   // wchar_t*
1297   wchar_t str[] = L"hi\1";
1298   wchar_t* p = str;
1299   EXPECT_STREQ("L\"hi\\x1\"",  // The string content should be escaped.
1300                FormatForComparisonFailureMessage(p, ::std::wstring()).c_str());
1301 }
1302 #endif
1303 
1304 // Tests formatting a char array when it's compared with a pointer or array.
1305 // In this case we want to print the array as a row pointer, as the comparison
1306 // is by pointer.
1307 
1308 // char array vs pointer
TEST(FormatForComparisonFailureMessageTest,WorksForCharArrayVsPointer)1309 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) {
1310   char str[] = "hi \"world\"";
1311   char* p = nullptr;
1312   EXPECT_EQ(PrintPointer(str),
1313             FormatForComparisonFailureMessage(str, p).c_str());
1314 }
1315 
1316 // char array vs char array
TEST(FormatForComparisonFailureMessageTest,WorksForCharArrayVsCharArray)1317 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) {
1318   const char str[] = "hi \"world\"";
1319   EXPECT_EQ(PrintPointer(str),
1320             FormatForComparisonFailureMessage(str, str).c_str());
1321 }
1322 
1323 // wchar_t array vs pointer
TEST(FormatForComparisonFailureMessageTest,WorksForWCharArrayVsPointer)1324 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) {
1325   wchar_t str[] = L"hi \"world\"";
1326   wchar_t* p = nullptr;
1327   EXPECT_EQ(PrintPointer(str),
1328             FormatForComparisonFailureMessage(str, p).c_str());
1329 }
1330 
1331 // wchar_t array vs wchar_t array
TEST(FormatForComparisonFailureMessageTest,WorksForWCharArrayVsWCharArray)1332 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) {
1333   const wchar_t str[] = L"hi \"world\"";
1334   EXPECT_EQ(PrintPointer(str),
1335             FormatForComparisonFailureMessage(str, str).c_str());
1336 }
1337 
1338 // Tests formatting a char array when it's compared with a string object.
1339 // In this case we want to print the array as a C string.
1340 
1341 #if GTEST_HAS_GLOBAL_STRING
1342 // char array vs string
TEST(FormatForComparisonFailureMessageTest,WorksForCharArrayVsString)1343 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsString) {
1344   const char str[] = "hi \"w\0rld\"";
1345   EXPECT_STREQ("\"hi \\\"w\"",  // The content should be escaped.
1346                                 // Embedded NUL terminates the string.
1347                FormatForComparisonFailureMessage(str, ::string()).c_str());
1348 }
1349 #endif
1350 
1351 // char array vs std::string
TEST(FormatForComparisonFailureMessageTest,WorksForCharArrayVsStdString)1352 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) {
1353   const char str[] = "hi \"world\"";
1354   EXPECT_STREQ("\"hi \\\"world\\\"\"",  // The content should be escaped.
1355                FormatForComparisonFailureMessage(str, ::std::string()).c_str());
1356 }
1357 
1358 #if GTEST_HAS_GLOBAL_WSTRING
1359 // wchar_t array vs wstring
TEST(FormatForComparisonFailureMessageTest,WorksForWCharArrayVsWString)1360 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWString) {
1361   const wchar_t str[] = L"hi \"world\"";
1362   EXPECT_STREQ("L\"hi \\\"world\\\"\"",  // The content should be escaped.
1363                FormatForComparisonFailureMessage(str, ::wstring()).c_str());
1364 }
1365 #endif
1366 
1367 #if GTEST_HAS_STD_WSTRING
1368 // wchar_t array vs std::wstring
TEST(FormatForComparisonFailureMessageTest,WorksForWCharArrayVsStdWString)1369 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
1370   const wchar_t str[] = L"hi \"w\0rld\"";
1371   EXPECT_STREQ(
1372       "L\"hi \\\"w\"",  // The content should be escaped.
1373                         // Embedded NUL terminates the string.
1374       FormatForComparisonFailureMessage(str, ::std::wstring()).c_str());
1375 }
1376 #endif
1377 
1378 // Useful for testing PrintToString().  We cannot use EXPECT_EQ()
1379 // there as its implementation uses PrintToString().  The caller must
1380 // ensure that 'value' has no side effect.
1381 #define EXPECT_PRINT_TO_STRING_(value, expected_string)         \
1382   EXPECT_TRUE(PrintToString(value) == (expected_string))        \
1383       << " where " #value " prints as " << (PrintToString(value))
1384 
TEST(PrintToStringTest,WorksForScalar)1385 TEST(PrintToStringTest, WorksForScalar) {
1386   EXPECT_PRINT_TO_STRING_(123, "123");
1387 }
1388 
TEST(PrintToStringTest,WorksForPointerToConstChar)1389 TEST(PrintToStringTest, WorksForPointerToConstChar) {
1390   const char* p = "hello";
1391   EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1392 }
1393 
TEST(PrintToStringTest,WorksForPointerToNonConstChar)1394 TEST(PrintToStringTest, WorksForPointerToNonConstChar) {
1395   char s[] = "hello";
1396   char* p = s;
1397   EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1398 }
1399 
TEST(PrintToStringTest,EscapesForPointerToConstChar)1400 TEST(PrintToStringTest, EscapesForPointerToConstChar) {
1401   const char* p = "hello\n";
1402   EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\"");
1403 }
1404 
TEST(PrintToStringTest,EscapesForPointerToNonConstChar)1405 TEST(PrintToStringTest, EscapesForPointerToNonConstChar) {
1406   char s[] = "hello\1";
1407   char* p = s;
1408   EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\"");
1409 }
1410 
TEST(PrintToStringTest,WorksForArray)1411 TEST(PrintToStringTest, WorksForArray) {
1412   int n[3] = { 1, 2, 3 };
1413   EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }");
1414 }
1415 
TEST(PrintToStringTest,WorksForCharArray)1416 TEST(PrintToStringTest, WorksForCharArray) {
1417   char s[] = "hello";
1418   EXPECT_PRINT_TO_STRING_(s, "\"hello\"");
1419 }
1420 
TEST(PrintToStringTest,WorksForCharArrayWithEmbeddedNul)1421 TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {
1422   const char str_with_nul[] = "hello\0 world";
1423   EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\"");
1424 
1425   char mutable_str_with_nul[] = "hello\0 world";
1426   EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\"");
1427 }
1428 
TEST(PrintToStringTest,ContainsNonLatin)1429   TEST(PrintToStringTest, ContainsNonLatin) {
1430   // Sanity test with valid UTF-8. Prints both in hex and as text.
1431   std::string non_ascii_str = ::std::string("오전 4:30");
1432   EXPECT_PRINT_TO_STRING_(non_ascii_str,
1433                           "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n"
1434                           "    As Text: \"오전 4:30\"");
1435   non_ascii_str = ::std::string("From ä — ẑ");
1436   EXPECT_PRINT_TO_STRING_(non_ascii_str,
1437                           "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\""
1438                           "\n    As Text: \"From ä — ẑ\"");
1439 }
1440 
TEST(IsValidUTF8Test,IllFormedUTF8)1441 TEST(IsValidUTF8Test, IllFormedUTF8) {
1442   // The following test strings are ill-formed UTF-8 and are printed
1443   // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is
1444   // expected to fail, thus output does not contain "As Text:".
1445 
1446   static const char *const kTestdata[][2] = {
1447     // 2-byte lead byte followed by a single-byte character.
1448     {"\xC3\x74", "\"\\xC3t\""},
1449     // Valid 2-byte character followed by an orphan trail byte.
1450     {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""},
1451     // Lead byte without trail byte.
1452     {"abc\xC3", "\"abc\\xC3\""},
1453     // 3-byte lead byte, single-byte character, orphan trail byte.
1454     {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""},
1455     // Truncated 3-byte character.
1456     {"\xE2\x80", "\"\\xE2\\x80\""},
1457     // Truncated 3-byte character followed by valid 2-byte char.
1458     {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""},
1459     // Truncated 3-byte character followed by a single-byte character.
1460     {"\xE2\x80\x7A", "\"\\xE2\\x80z\""},
1461     // 3-byte lead byte followed by valid 3-byte character.
1462     {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""},
1463     // 4-byte lead byte followed by valid 3-byte character.
1464     {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""},
1465     // Truncated 4-byte character.
1466     {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""},
1467      // Invalid UTF-8 byte sequences embedded in other chars.
1468     {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""},
1469     {"abc\xC3\x84\xE2\x80\xC3\x84xyz",
1470      "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""},
1471     // Non-shortest UTF-8 byte sequences are also ill-formed.
1472     // The classics: xC0, xC1 lead byte.
1473     {"\xC0\x80", "\"\\xC0\\x80\""},
1474     {"\xC1\x81", "\"\\xC1\\x81\""},
1475     // Non-shortest sequences.
1476     {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
1477     {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
1478     // Last valid code point before surrogate range, should be printed as text,
1479     // too.
1480     {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n    As Text: \"퟿\""},
1481     // Start of surrogate lead. Surrogates are not printed as text.
1482     {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""},
1483     // Last non-private surrogate lead.
1484     {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""},
1485     // First private-use surrogate lead.
1486     {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""},
1487     // Last private-use surrogate lead.
1488     {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
1489     // Mid-point of surrogate trail.
1490     {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
1491     // First valid code point after surrogate range, should be printed as text,
1492     // too.
1493     {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n    As Text: \"\""}
1494   };
1495 
1496   for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) {
1497     EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
1498   }
1499 }
1500 
1501 #undef EXPECT_PRINT_TO_STRING_
1502 
TEST(UniversalTersePrintTest,WorksForNonReference)1503 TEST(UniversalTersePrintTest, WorksForNonReference) {
1504   ::std::stringstream ss;
1505   UniversalTersePrint(123, &ss);
1506   EXPECT_EQ("123", ss.str());
1507 }
1508 
TEST(UniversalTersePrintTest,WorksForReference)1509 TEST(UniversalTersePrintTest, WorksForReference) {
1510   const int& n = 123;
1511   ::std::stringstream ss;
1512   UniversalTersePrint(n, &ss);
1513   EXPECT_EQ("123", ss.str());
1514 }
1515 
TEST(UniversalTersePrintTest,WorksForCString)1516 TEST(UniversalTersePrintTest, WorksForCString) {
1517   const char* s1 = "abc";
1518   ::std::stringstream ss1;
1519   UniversalTersePrint(s1, &ss1);
1520   EXPECT_EQ("\"abc\"", ss1.str());
1521 
1522   char* s2 = const_cast<char*>(s1);
1523   ::std::stringstream ss2;
1524   UniversalTersePrint(s2, &ss2);
1525   EXPECT_EQ("\"abc\"", ss2.str());
1526 
1527   const char* s3 = nullptr;
1528   ::std::stringstream ss3;
1529   UniversalTersePrint(s3, &ss3);
1530   EXPECT_EQ("NULL", ss3.str());
1531 }
1532 
TEST(UniversalPrintTest,WorksForNonReference)1533 TEST(UniversalPrintTest, WorksForNonReference) {
1534   ::std::stringstream ss;
1535   UniversalPrint(123, &ss);
1536   EXPECT_EQ("123", ss.str());
1537 }
1538 
TEST(UniversalPrintTest,WorksForReference)1539 TEST(UniversalPrintTest, WorksForReference) {
1540   const int& n = 123;
1541   ::std::stringstream ss;
1542   UniversalPrint(n, &ss);
1543   EXPECT_EQ("123", ss.str());
1544 }
1545 
TEST(UniversalPrintTest,WorksForCString)1546 TEST(UniversalPrintTest, WorksForCString) {
1547   const char* s1 = "abc";
1548   ::std::stringstream ss1;
1549   UniversalPrint(s1, &ss1);
1550   EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str()));
1551 
1552   char* s2 = const_cast<char*>(s1);
1553   ::std::stringstream ss2;
1554   UniversalPrint(s2, &ss2);
1555   EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str()));
1556 
1557   const char* s3 = nullptr;
1558   ::std::stringstream ss3;
1559   UniversalPrint(s3, &ss3);
1560   EXPECT_EQ("NULL", ss3.str());
1561 }
1562 
TEST(UniversalPrintTest,WorksForCharArray)1563 TEST(UniversalPrintTest, WorksForCharArray) {
1564   const char str[] = "\"Line\0 1\"\nLine 2";
1565   ::std::stringstream ss1;
1566   UniversalPrint(str, &ss1);
1567   EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str());
1568 
1569   const char mutable_str[] = "\"Line\0 1\"\nLine 2";
1570   ::std::stringstream ss2;
1571   UniversalPrint(mutable_str, &ss2);
1572   EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str());
1573 }
1574 
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd,PrintsEmptyTuple)1575 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
1576   Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
1577   EXPECT_EQ(0u, result.size());
1578 }
1579 
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd,PrintsOneTuple)1580 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
1581   Strings result = UniversalTersePrintTupleFieldsToStrings(
1582       ::std::make_tuple(1));
1583   ASSERT_EQ(1u, result.size());
1584   EXPECT_EQ("1", result[0]);
1585 }
1586 
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd,PrintsTwoTuple)1587 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
1588   Strings result = UniversalTersePrintTupleFieldsToStrings(
1589       ::std::make_tuple(1, 'a'));
1590   ASSERT_EQ(2u, result.size());
1591   EXPECT_EQ("1", result[0]);
1592   EXPECT_EQ("'a' (97, 0x61)", result[1]);
1593 }
1594 
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd,PrintsTersely)1595 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
1596   const int n = 1;
1597   Strings result = UniversalTersePrintTupleFieldsToStrings(
1598       ::std::tuple<const int&, const char*>(n, "a"));
1599   ASSERT_EQ(2u, result.size());
1600   EXPECT_EQ("1", result[0]);
1601   EXPECT_EQ("\"a\"", result[1]);
1602 }
1603 
1604 #if GTEST_HAS_ABSL
1605 
TEST(PrintOptionalTest,Basic)1606 TEST(PrintOptionalTest, Basic) {
1607   absl::optional<int> value;
1608   EXPECT_EQ("(nullopt)", PrintToString(value));
1609   value = {7};
1610   EXPECT_EQ("(7)", PrintToString(value));
1611   EXPECT_EQ("(1.1)", PrintToString(absl::optional<double>{1.1}));
1612   EXPECT_EQ("(\"A\")", PrintToString(absl::optional<std::string>{"A"}));
1613 }
1614 
1615 struct NonPrintable {
1616   unsigned char contents = 17;
1617 };
1618 
TEST(PrintOneofTest,Basic)1619 TEST(PrintOneofTest, Basic) {
1620   using Type = absl::variant<int, StreamableInGlobal, NonPrintable>;
1621   EXPECT_EQ("('int' with value 7)", PrintToString(Type(7)));
1622   EXPECT_EQ("('StreamableInGlobal' with value StreamableInGlobal)",
1623             PrintToString(Type(StreamableInGlobal{})));
1624   EXPECT_EQ(
1625       "('testing::gtest_printers_test::NonPrintable' with value 1-byte object "
1626       "<11>)",
1627       PrintToString(Type(NonPrintable{})));
1628 }
1629 #endif  // GTEST_HAS_ABSL
1630 
1631 }  // namespace gtest_printers_test
1632 }  // namespace testing
1633