• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <algorithm>
36 #include <cctype>
37 #include <cstdint>
38 #include <cstring>
39 #include <deque>
40 #include <forward_list>
41 #include <limits>
42 #include <list>
43 #include <map>
44 #include <memory>
45 #include <set>
46 #include <sstream>
47 #include <string>
48 #include <unordered_map>
49 #include <unordered_set>
50 #include <utility>
51 #include <vector>
52 
53 #include "gtest/gtest-printers.h"
54 #include "gtest/gtest.h"
55 
56 // Some user-defined types for testing the universal value printer.
57 
58 // An anonymous enum type.
59 enum AnonymousEnum {
60   kAE1 = -1,
61   kAE2 = 1
62 };
63 
64 // An enum without a user-defined printer.
65 enum EnumWithoutPrinter {
66   kEWP1 = -2,
67   kEWP2 = 42
68 };
69 
70 // An enum with a << operator.
71 enum EnumWithStreaming {
72   kEWS1 = 10
73 };
74 
operator <<(std::ostream & os,EnumWithStreaming e)75 std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
76   return os << (e == kEWS1 ? "kEWS1" : "invalid");
77 }
78 
79 // An enum with a PrintTo() function.
80 enum EnumWithPrintTo {
81   kEWPT1 = 1
82 };
83 
PrintTo(EnumWithPrintTo e,std::ostream * os)84 void PrintTo(EnumWithPrintTo e, std::ostream* os) {
85   *os << (e == kEWPT1 ? "kEWPT1" : "invalid");
86 }
87 
88 // A class implicitly convertible to BiggestInt.
89 class BiggestIntConvertible {
90  public:
operator ::testing::internal::BiggestInt() const91   operator ::testing::internal::BiggestInt() const { return 42; }
92 };
93 
94 // A parent class with two child classes. The parent and one of the kids have
95 // stream operators.
96 class ParentClass {};
97 class ChildClassWithStreamOperator : public ParentClass {};
98 class ChildClassWithoutStreamOperator : public ParentClass {};
operator <<(std::ostream & os,const ParentClass &)99 static void operator<<(std::ostream& os, const ParentClass&) {
100   os << "ParentClass";
101 }
operator <<(std::ostream & os,const ChildClassWithStreamOperator &)102 static void operator<<(std::ostream& os, const ChildClassWithStreamOperator&) {
103   os << "ChildClassWithStreamOperator";
104 }
105 
106 // A user-defined unprintable class template in the global namespace.
107 template <typename T>
108 class UnprintableTemplateInGlobal {
109  public:
UnprintableTemplateInGlobal()110   UnprintableTemplateInGlobal() : value_() {}
111  private:
112   T value_;
113 };
114 
115 // A user-defined streamable type in the global namespace.
116 class StreamableInGlobal {
117  public:
~StreamableInGlobal()118   virtual ~StreamableInGlobal() {}
119 };
120 
operator <<(::std::ostream & os,const StreamableInGlobal &)121 inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) {
122   os << "StreamableInGlobal";
123 }
124 
operator <<(::std::ostream & os,const StreamableInGlobal *)125 void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) {
126   os << "StreamableInGlobal*";
127 }
128 
129 namespace foo {
130 
131 // A user-defined unprintable type in a user namespace.
132 class UnprintableInFoo {
133  public:
UnprintableInFoo()134   UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
z() const135   double z() const { return z_; }
136  private:
137   char xy_[8];
138   double z_;
139 };
140 
141 // A user-defined printable type in a user-chosen namespace.
142 struct PrintableViaPrintTo {
PrintableViaPrintTofoo::PrintableViaPrintTo143   PrintableViaPrintTo() : value() {}
144   int value;
145 };
146 
PrintTo(const PrintableViaPrintTo & x,::std::ostream * os)147 void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
148   *os << "PrintableViaPrintTo: " << x.value;
149 }
150 
151 // A type with a user-defined << for printing its pointer.
152 struct PointerPrintable {
153 };
154 
operator <<(::std::ostream & os,const PointerPrintable *)155 ::std::ostream& operator<<(::std::ostream& os,
156                            const PointerPrintable* /* x */) {
157   return os << "PointerPrintable*";
158 }
159 
160 // A user-defined printable class template in a user-chosen namespace.
161 template <typename T>
162 class PrintableViaPrintToTemplate {
163  public:
PrintableViaPrintToTemplate(const T & a_value)164   explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
165 
value() const166   const T& value() const { return value_; }
167  private:
168   T value_;
169 };
170 
171 template <typename T>
PrintTo(const PrintableViaPrintToTemplate<T> & x,::std::ostream * os)172 void PrintTo(const PrintableViaPrintToTemplate<T>& x, ::std::ostream* os) {
173   *os << "PrintableViaPrintToTemplate: " << x.value();
174 }
175 
176 // A user-defined streamable class template in a user namespace.
177 template <typename T>
178 class StreamableTemplateInFoo {
179  public:
StreamableTemplateInFoo()180   StreamableTemplateInFoo() : value_() {}
181 
value() const182   const T& value() const { return value_; }
183  private:
184   T value_;
185 };
186 
187 template <typename T>
operator <<(::std::ostream & os,const StreamableTemplateInFoo<T> & x)188 inline ::std::ostream& operator<<(::std::ostream& os,
189                                   const StreamableTemplateInFoo<T>& x) {
190   return os << "StreamableTemplateInFoo: " << x.value();
191 }
192 
193 // A user-defined streamable type in a user namespace whose operator<< is
194 // templated on the type of the output stream.
195 struct TemplatedStreamableInFoo {};
196 
197 template <typename OutputStream>
operator <<(OutputStream & os,const TemplatedStreamableInFoo &)198 OutputStream& operator<<(OutputStream& os,
199                          const TemplatedStreamableInFoo& /*ts*/) {
200   os << "TemplatedStreamableInFoo";
201   return os;
202 }
203 
204 // A user-defined streamable but recursively-defined container type in
205 // a user namespace, it mimics therefore std::filesystem::path or
206 // boost::filesystem::path.
207 class PathLike {
208  public:
209   struct iterator {
210     typedef PathLike value_type;
211 
212     iterator& operator++();
213     PathLike& operator*();
214   };
215 
216   using value_type = char;
217   using const_iterator = iterator;
218 
PathLike()219   PathLike() {}
220 
begin() const221   iterator begin() const { return iterator(); }
end() const222   iterator end() const { return iterator(); }
223 
operator <<(::std::ostream & os,const PathLike &)224   friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) {
225     return os << "Streamable-PathLike";
226   }
227 };
228 
229 }  // namespace foo
230 
231 namespace testing {
232 namespace {
233 template <typename T>
234 class Wrapper {
235  public:
Wrapper(T && value)236   explicit Wrapper(T&& value) : value_(std::forward<T>(value)) {}
237 
value() const238   const T& value() const { return value_; }
239 
240  private:
241   T value_;
242 };
243 
244 }  // namespace
245 
246 namespace internal {
247 template <typename T>
248 class UniversalPrinter<Wrapper<T>> {
249  public:
Print(const Wrapper<T> & w,::std::ostream * os)250   static void Print(const Wrapper<T>& w, ::std::ostream* os) {
251     *os << "Wrapper(";
252     UniversalPrint(w.value(), os);
253     *os << ')';
254   }
255 };
256 }  // namespace internal
257 
258 
259 namespace gtest_printers_test {
260 
261 using ::std::deque;
262 using ::std::list;
263 using ::std::make_pair;
264 using ::std::map;
265 using ::std::multimap;
266 using ::std::multiset;
267 using ::std::pair;
268 using ::std::set;
269 using ::std::vector;
270 using ::testing::PrintToString;
271 using ::testing::internal::FormatForComparisonFailureMessage;
272 using ::testing::internal::ImplicitCast_;
273 using ::testing::internal::NativeArray;
274 using ::testing::internal::RelationToSourceReference;
275 using ::testing::internal::Strings;
276 using ::testing::internal::UniversalPrint;
277 using ::testing::internal::UniversalPrinter;
278 using ::testing::internal::UniversalTersePrint;
279 using ::testing::internal::UniversalTersePrintTupleFieldsToStrings;
280 
281 // Prints a value to a string using the universal value printer.  This
282 // is a helper for testing UniversalPrinter<T>::Print() for various types.
283 template <typename T>
Print(const T & value)284 std::string Print(const T& value) {
285   ::std::stringstream ss;
286   UniversalPrinter<T>::Print(value, &ss);
287   return ss.str();
288 }
289 
290 // Prints a value passed by reference to a string, using the universal
291 // value printer.  This is a helper for testing
292 // UniversalPrinter<T&>::Print() for various types.
293 template <typename T>
PrintByRef(const T & value)294 std::string PrintByRef(const T& value) {
295   ::std::stringstream ss;
296   UniversalPrinter<T&>::Print(value, &ss);
297   return ss.str();
298 }
299 
300 // Tests printing various enum types.
301 
TEST(PrintEnumTest,AnonymousEnum)302 TEST(PrintEnumTest, AnonymousEnum) {
303   EXPECT_EQ("-1", Print(kAE1));
304   EXPECT_EQ("1", Print(kAE2));
305 }
306 
TEST(PrintEnumTest,EnumWithoutPrinter)307 TEST(PrintEnumTest, EnumWithoutPrinter) {
308   EXPECT_EQ("-2", Print(kEWP1));
309   EXPECT_EQ("42", Print(kEWP2));
310 }
311 
TEST(PrintEnumTest,EnumWithStreaming)312 TEST(PrintEnumTest, EnumWithStreaming) {
313   EXPECT_EQ("kEWS1", Print(kEWS1));
314   EXPECT_EQ("invalid", Print(static_cast<EnumWithStreaming>(0)));
315 }
316 
TEST(PrintEnumTest,EnumWithPrintTo)317 TEST(PrintEnumTest, EnumWithPrintTo) {
318   EXPECT_EQ("kEWPT1", Print(kEWPT1));
319   EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0)));
320 }
321 
322 // Tests printing a class implicitly convertible to BiggestInt.
323 
TEST(PrintClassTest,BiggestIntConvertible)324 TEST(PrintClassTest, BiggestIntConvertible) {
325   EXPECT_EQ("42", Print(BiggestIntConvertible()));
326 }
327 
328 // Tests printing various char types.
329 
330 // char.
TEST(PrintCharTest,PlainChar)331 TEST(PrintCharTest, PlainChar) {
332   EXPECT_EQ("'\\0'", Print('\0'));
333   EXPECT_EQ("'\\'' (39, 0x27)", Print('\''));
334   EXPECT_EQ("'\"' (34, 0x22)", Print('"'));
335   EXPECT_EQ("'?' (63, 0x3F)", Print('?'));
336   EXPECT_EQ("'\\\\' (92, 0x5C)", Print('\\'));
337   EXPECT_EQ("'\\a' (7)", Print('\a'));
338   EXPECT_EQ("'\\b' (8)", Print('\b'));
339   EXPECT_EQ("'\\f' (12, 0xC)", Print('\f'));
340   EXPECT_EQ("'\\n' (10, 0xA)", Print('\n'));
341   EXPECT_EQ("'\\r' (13, 0xD)", Print('\r'));
342   EXPECT_EQ("'\\t' (9)", Print('\t'));
343   EXPECT_EQ("'\\v' (11, 0xB)", Print('\v'));
344   EXPECT_EQ("'\\x7F' (127)", Print('\x7F'));
345   EXPECT_EQ("'\\xFF' (255)", Print('\xFF'));
346   EXPECT_EQ("' ' (32, 0x20)", Print(' '));
347   EXPECT_EQ("'a' (97, 0x61)", Print('a'));
348 }
349 
350 // signed char.
TEST(PrintCharTest,SignedChar)351 TEST(PrintCharTest, SignedChar) {
352   EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0')));
353   EXPECT_EQ("'\\xCE' (-50)",
354             Print(static_cast<signed char>(-50)));
355 }
356 
357 // unsigned char.
TEST(PrintCharTest,UnsignedChar)358 TEST(PrintCharTest, UnsignedChar) {
359   EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0')));
360   EXPECT_EQ("'b' (98, 0x62)",
361             Print(static_cast<unsigned char>('b')));
362 }
363 
TEST(PrintCharTest,Char16)364 TEST(PrintCharTest, Char16) {
365   EXPECT_EQ("U+0041", Print(u'A'));
366 }
367 
TEST(PrintCharTest,Char32)368 TEST(PrintCharTest, Char32) {
369   EXPECT_EQ("U+0041", Print(U'A'));
370 }
371 
372 #ifdef __cpp_char8_t
TEST(PrintCharTest,Char8)373 TEST(PrintCharTest, Char8) {
374   EXPECT_EQ("U+0041", Print(u8'A'));
375 }
376 #endif
377 
378 // Tests printing other simple, built-in types.
379 
380 // bool.
TEST(PrintBuiltInTypeTest,Bool)381 TEST(PrintBuiltInTypeTest, Bool) {
382   EXPECT_EQ("false", Print(false));
383   EXPECT_EQ("true", Print(true));
384 }
385 
386 // wchar_t.
TEST(PrintBuiltInTypeTest,Wchar_t)387 TEST(PrintBuiltInTypeTest, Wchar_t) {
388   EXPECT_EQ("L'\\0'", Print(L'\0'));
389   EXPECT_EQ("L'\\'' (39, 0x27)", Print(L'\''));
390   EXPECT_EQ("L'\"' (34, 0x22)", Print(L'"'));
391   EXPECT_EQ("L'?' (63, 0x3F)", Print(L'?'));
392   EXPECT_EQ("L'\\\\' (92, 0x5C)", Print(L'\\'));
393   EXPECT_EQ("L'\\a' (7)", Print(L'\a'));
394   EXPECT_EQ("L'\\b' (8)", Print(L'\b'));
395   EXPECT_EQ("L'\\f' (12, 0xC)", Print(L'\f'));
396   EXPECT_EQ("L'\\n' (10, 0xA)", Print(L'\n'));
397   EXPECT_EQ("L'\\r' (13, 0xD)", Print(L'\r'));
398   EXPECT_EQ("L'\\t' (9)", Print(L'\t'));
399   EXPECT_EQ("L'\\v' (11, 0xB)", Print(L'\v'));
400   EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F'));
401   EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF'));
402   EXPECT_EQ("L' ' (32, 0x20)", Print(L' '));
403   EXPECT_EQ("L'a' (97, 0x61)", Print(L'a'));
404   EXPECT_EQ("L'\\x576' (1398)", Print(static_cast<wchar_t>(0x576)));
405   EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast<wchar_t>(0xC74D)));
406 }
407 
408 // Test that int64_t provides more storage than wchar_t.
TEST(PrintTypeSizeTest,Wchar_t)409 TEST(PrintTypeSizeTest, Wchar_t) {
410   EXPECT_LT(sizeof(wchar_t), sizeof(int64_t));
411 }
412 
413 // Various integer types.
TEST(PrintBuiltInTypeTest,Integer)414 TEST(PrintBuiltInTypeTest, Integer) {
415   EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255)));  // uint8
416   EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128)));  // int8
417   EXPECT_EQ("65535", Print(std::numeric_limits<uint16_t>::max()));  // uint16
418   EXPECT_EQ("-32768", Print(std::numeric_limits<int16_t>::min()));  // int16
419   EXPECT_EQ("4294967295",
420             Print(std::numeric_limits<uint32_t>::max()));  // uint32
421   EXPECT_EQ("-2147483648",
422             Print(std::numeric_limits<int32_t>::min()));  // int32
423   EXPECT_EQ("18446744073709551615",
424             Print(std::numeric_limits<uint64_t>::max()));  // uint64
425   EXPECT_EQ("-9223372036854775808",
426             Print(std::numeric_limits<int64_t>::min()));  // int64
427 #ifdef __cpp_char8_t
428   EXPECT_EQ("U+0000",
429             Print(std::numeric_limits<char8_t>::min()));  // char8_t
430   EXPECT_EQ("U+00FF",
431             Print(std::numeric_limits<char8_t>::max()));  // char8_t
432 #endif
433   EXPECT_EQ("U+0000",
434             Print(std::numeric_limits<char16_t>::min()));  // char16_t
435   EXPECT_EQ("U+FFFF",
436             Print(std::numeric_limits<char16_t>::max()));  // char16_t
437   EXPECT_EQ("U+0000",
438             Print(std::numeric_limits<char32_t>::min()));  // char32_t
439   EXPECT_EQ("U+FFFFFFFF",
440             Print(std::numeric_limits<char32_t>::max()));  // char32_t
441 }
442 
443 // Size types.
TEST(PrintBuiltInTypeTest,Size_t)444 TEST(PrintBuiltInTypeTest, Size_t) {
445   EXPECT_EQ("1", Print(sizeof('a')));  // size_t.
446 #if !GTEST_OS_WINDOWS
447   // Windows has no ssize_t type.
448   EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2)));  // ssize_t.
449 #endif  // !GTEST_OS_WINDOWS
450 }
451 
452 // gcc/clang __{u,}int128_t values.
453 #if defined(__SIZEOF_INT128__)
TEST(PrintBuiltInTypeTest,Int128)454 TEST(PrintBuiltInTypeTest, Int128) {
455   // Small ones
456   EXPECT_EQ("0", Print(__int128_t{0}));
457   EXPECT_EQ("0", Print(__uint128_t{0}));
458   EXPECT_EQ("12345", Print(__int128_t{12345}));
459   EXPECT_EQ("12345", Print(__uint128_t{12345}));
460   EXPECT_EQ("-12345", Print(__int128_t{-12345}));
461 
462   // Large ones
463   EXPECT_EQ("340282366920938463463374607431768211455", Print(~__uint128_t{}));
464   __int128_t max_128 = static_cast<__int128_t>(~__uint128_t{} / 2);
465   EXPECT_EQ("-170141183460469231731687303715884105728", Print(~max_128));
466   EXPECT_EQ("170141183460469231731687303715884105727", Print(max_128));
467 }
468 #endif  // __SIZEOF_INT128__
469 
470 // Floating-points.
TEST(PrintBuiltInTypeTest,FloatingPoints)471 TEST(PrintBuiltInTypeTest, FloatingPoints) {
472   EXPECT_EQ("1.5", Print(1.5f));   // float
473   EXPECT_EQ("-2.5", Print(-2.5));  // double
474 }
475 
476 #if GTEST_HAS_RTTI
TEST(PrintBuiltInTypeTest,TypeInfo)477 TEST(PrintBuiltInTypeTest, TypeInfo) {
478   struct MyStruct {};
479   auto res = Print(typeid(MyStruct{}));
480   // We can't guarantee that we can demangle the name, but either name should
481   // contain the substring "MyStruct".
482   EXPECT_NE(res.find("MyStruct"), res.npos) << res;
483 }
484 #endif  // GTEST_HAS_RTTI
485 
486 // Since ::std::stringstream::operator<<(const void *) formats the pointer
487 // output differently with different compilers, we have to create the expected
488 // output first and use it as our expectation.
PrintPointer(const void * p)489 static std::string PrintPointer(const void* p) {
490   ::std::stringstream expected_result_stream;
491   expected_result_stream << p;
492   return expected_result_stream.str();
493 }
494 
495 // Tests printing C strings.
496 
497 // const char*.
TEST(PrintCStringTest,Const)498 TEST(PrintCStringTest, Const) {
499   const char* p = "World";
500   EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p));
501 }
502 
503 // char*.
TEST(PrintCStringTest,NonConst)504 TEST(PrintCStringTest, NonConst) {
505   char p[] = "Hi";
506   EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"",
507             Print(static_cast<char*>(p)));
508 }
509 
510 // NULL C string.
TEST(PrintCStringTest,Null)511 TEST(PrintCStringTest, Null) {
512   const char* p = nullptr;
513   EXPECT_EQ("NULL", Print(p));
514 }
515 
516 // Tests that C strings are escaped properly.
TEST(PrintCStringTest,EscapesProperly)517 TEST(PrintCStringTest, EscapesProperly) {
518   const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
519   EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f"
520             "\\n\\r\\t\\v\\x7F\\xFF a\"",
521             Print(p));
522 }
523 
524 #ifdef __cpp_char8_t
525 // const char8_t*.
TEST(PrintU8StringTest,Const)526 TEST(PrintU8StringTest, Const) {
527   const char8_t* p = u8"界";
528   EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE7\\x95\\x8C\"", Print(p));
529 }
530 
531 // char8_t*.
TEST(PrintU8StringTest,NonConst)532 TEST(PrintU8StringTest, NonConst) {
533   char8_t p[] = u8"世";
534   EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE4\\xB8\\x96\"",
535             Print(static_cast<char8_t*>(p)));
536 }
537 
538 // NULL u8 string.
TEST(PrintU8StringTest,Null)539 TEST(PrintU8StringTest, Null) {
540   const char8_t* p = nullptr;
541   EXPECT_EQ("NULL", Print(p));
542 }
543 
544 // Tests that u8 strings are escaped properly.
TEST(PrintU8StringTest,EscapesProperly)545 TEST(PrintU8StringTest, EscapesProperly) {
546   const char8_t* p = u8"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 世界";
547   EXPECT_EQ(PrintPointer(p) +
548                 " pointing to u8\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
549                 "hello \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
550             Print(p));
551 }
552 #endif
553 
554 // const char16_t*.
TEST(PrintU16StringTest,Const)555 TEST(PrintU16StringTest, Const) {
556   const char16_t* p = u"界";
557   EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x754C\"", Print(p));
558 }
559 
560 // char16_t*.
TEST(PrintU16StringTest,NonConst)561 TEST(PrintU16StringTest, NonConst) {
562   char16_t p[] = u"世";
563   EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x4E16\"",
564             Print(static_cast<char16_t*>(p)));
565 }
566 
567 // NULL u16 string.
TEST(PrintU16StringTest,Null)568 TEST(PrintU16StringTest, Null) {
569   const char16_t* p = nullptr;
570   EXPECT_EQ("NULL", Print(p));
571 }
572 
573 // Tests that u16 strings are escaped properly.
TEST(PrintU16StringTest,EscapesProperly)574 TEST(PrintU16StringTest, EscapesProperly) {
575   const char16_t* p = u"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 世界";
576   EXPECT_EQ(PrintPointer(p) +
577                 " pointing to u\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
578                 "hello \\x4E16\\x754C\"",
579             Print(p));
580 }
581 
582 // const char32_t*.
TEST(PrintU32StringTest,Const)583 TEST(PrintU32StringTest, Const) {
584   const char32_t* p = U"��️";
585   EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F5FA\\xFE0F\"", Print(p));
586 }
587 
588 // char32_t*.
TEST(PrintU32StringTest,NonConst)589 TEST(PrintU32StringTest, NonConst) {
590   char32_t p[] = U"��";
591   EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F30C\"",
592             Print(static_cast<char32_t*>(p)));
593 }
594 
595 // NULL u32 string.
TEST(PrintU32StringTest,Null)596 TEST(PrintU32StringTest, Null) {
597   const char32_t* p = nullptr;
598   EXPECT_EQ("NULL", Print(p));
599 }
600 
601 // Tests that u32 strings are escaped properly.
TEST(PrintU32StringTest,EscapesProperly)602 TEST(PrintU32StringTest, EscapesProperly) {
603   const char32_t* p = U"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello ��️";
604   EXPECT_EQ(PrintPointer(p) +
605                 " pointing to U\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
606                 "hello \\x1F5FA\\xFE0F\"",
607             Print(p));
608 }
609 
610 // MSVC compiler can be configured to define whar_t as a typedef
611 // of unsigned short. Defining an overload for const wchar_t* in that case
612 // would cause pointers to unsigned shorts be printed as wide strings,
613 // possibly accessing more memory than intended and causing invalid
614 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
615 // wchar_t is implemented as a native type.
616 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
617 
618 // const wchar_t*.
TEST(PrintWideCStringTest,Const)619 TEST(PrintWideCStringTest, Const) {
620   const wchar_t* p = L"World";
621   EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p));
622 }
623 
624 // wchar_t*.
TEST(PrintWideCStringTest,NonConst)625 TEST(PrintWideCStringTest, NonConst) {
626   wchar_t p[] = L"Hi";
627   EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"",
628             Print(static_cast<wchar_t*>(p)));
629 }
630 
631 // NULL wide C string.
TEST(PrintWideCStringTest,Null)632 TEST(PrintWideCStringTest, Null) {
633   const wchar_t* p = nullptr;
634   EXPECT_EQ("NULL", Print(p));
635 }
636 
637 // Tests that wide C strings are escaped properly.
TEST(PrintWideCStringTest,EscapesProperly)638 TEST(PrintWideCStringTest, EscapesProperly) {
639   const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r',
640                        '\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'};
641   EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f"
642             "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
643             Print(static_cast<const wchar_t*>(s)));
644 }
645 #endif  // native wchar_t
646 
647 // Tests printing pointers to other char types.
648 
649 // signed char*.
TEST(PrintCharPointerTest,SignedChar)650 TEST(PrintCharPointerTest, SignedChar) {
651   signed char* p = reinterpret_cast<signed char*>(0x1234);
652   EXPECT_EQ(PrintPointer(p), Print(p));
653   p = nullptr;
654   EXPECT_EQ("NULL", Print(p));
655 }
656 
657 // const signed char*.
TEST(PrintCharPointerTest,ConstSignedChar)658 TEST(PrintCharPointerTest, ConstSignedChar) {
659   signed char* p = reinterpret_cast<signed char*>(0x1234);
660   EXPECT_EQ(PrintPointer(p), Print(p));
661   p = nullptr;
662   EXPECT_EQ("NULL", Print(p));
663 }
664 
665 // unsigned char*.
TEST(PrintCharPointerTest,UnsignedChar)666 TEST(PrintCharPointerTest, UnsignedChar) {
667   unsigned char* p = reinterpret_cast<unsigned char*>(0x1234);
668   EXPECT_EQ(PrintPointer(p), Print(p));
669   p = nullptr;
670   EXPECT_EQ("NULL", Print(p));
671 }
672 
673 // const unsigned char*.
TEST(PrintCharPointerTest,ConstUnsignedChar)674 TEST(PrintCharPointerTest, ConstUnsignedChar) {
675   const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234);
676   EXPECT_EQ(PrintPointer(p), Print(p));
677   p = nullptr;
678   EXPECT_EQ("NULL", Print(p));
679 }
680 
681 // Tests printing pointers to simple, built-in types.
682 
683 // bool*.
TEST(PrintPointerToBuiltInTypeTest,Bool)684 TEST(PrintPointerToBuiltInTypeTest, Bool) {
685   bool* p = reinterpret_cast<bool*>(0xABCD);
686   EXPECT_EQ(PrintPointer(p), Print(p));
687   p = nullptr;
688   EXPECT_EQ("NULL", Print(p));
689 }
690 
691 // void*.
TEST(PrintPointerToBuiltInTypeTest,Void)692 TEST(PrintPointerToBuiltInTypeTest, Void) {
693   void* p = reinterpret_cast<void*>(0xABCD);
694   EXPECT_EQ(PrintPointer(p), Print(p));
695   p = nullptr;
696   EXPECT_EQ("NULL", Print(p));
697 }
698 
699 // const void*.
TEST(PrintPointerToBuiltInTypeTest,ConstVoid)700 TEST(PrintPointerToBuiltInTypeTest, ConstVoid) {
701   const void* p = reinterpret_cast<const void*>(0xABCD);
702   EXPECT_EQ(PrintPointer(p), Print(p));
703   p = nullptr;
704   EXPECT_EQ("NULL", Print(p));
705 }
706 
707 // Tests printing pointers to pointers.
TEST(PrintPointerToPointerTest,IntPointerPointer)708 TEST(PrintPointerToPointerTest, IntPointerPointer) {
709   int** p = reinterpret_cast<int**>(0xABCD);
710   EXPECT_EQ(PrintPointer(p), Print(p));
711   p = nullptr;
712   EXPECT_EQ("NULL", Print(p));
713 }
714 
715 // Tests printing (non-member) function pointers.
716 
MyFunction(int)717 void MyFunction(int /* n */) {}
718 
TEST(PrintPointerTest,NonMemberFunctionPointer)719 TEST(PrintPointerTest, NonMemberFunctionPointer) {
720   // We cannot directly cast &MyFunction to const void* because the
721   // standard disallows casting between pointers to functions and
722   // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
723   // this limitation.
724   EXPECT_EQ(
725       PrintPointer(reinterpret_cast<const void*>(
726           reinterpret_cast<internal::BiggestInt>(&MyFunction))),
727       Print(&MyFunction));
728   int (*p)(bool) = NULL;  // NOLINT
729   EXPECT_EQ("NULL", Print(p));
730 }
731 
732 // An assertion predicate determining whether a one string is a prefix for
733 // another.
734 template <typename StringType>
HasPrefix(const StringType & str,const StringType & prefix)735 AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
736   if (str.find(prefix, 0) == 0)
737     return AssertionSuccess();
738 
739   const bool is_wide_string = sizeof(prefix[0]) > 1;
740   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
741   return AssertionFailure()
742       << begin_string_quote << prefix << "\" is not a prefix of "
743       << begin_string_quote << str << "\"\n";
744 }
745 
746 // Tests printing member variable pointers.  Although they are called
747 // pointers, they don't point to a location in the address space.
748 // Their representation is implementation-defined.  Thus they will be
749 // printed as raw bytes.
750 
751 struct Foo {
752  public:
~Footesting::gtest_printers_test::Foo753   virtual ~Foo() {}
MyMethodtesting::gtest_printers_test::Foo754   int MyMethod(char x) { return x + 1; }
MyVirtualMethodtesting::gtest_printers_test::Foo755   virtual char MyVirtualMethod(int /* n */) { return 'a'; }
756 
757   int value;
758 };
759 
TEST(PrintPointerTest,MemberVariablePointer)760 TEST(PrintPointerTest, MemberVariablePointer) {
761   EXPECT_TRUE(HasPrefix(Print(&Foo::value),
762                         Print(sizeof(&Foo::value)) + "-byte object "));
763   int Foo::*p = NULL;  // NOLINT
764   EXPECT_TRUE(HasPrefix(Print(p),
765                         Print(sizeof(p)) + "-byte object "));
766 }
767 
768 // Tests printing member function pointers.  Although they are called
769 // pointers, they don't point to a location in the address space.
770 // Their representation is implementation-defined.  Thus they will be
771 // printed as raw bytes.
TEST(PrintPointerTest,MemberFunctionPointer)772 TEST(PrintPointerTest, MemberFunctionPointer) {
773   EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod),
774                         Print(sizeof(&Foo::MyMethod)) + "-byte object "));
775   EXPECT_TRUE(
776       HasPrefix(Print(&Foo::MyVirtualMethod),
777                 Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
778   int (Foo::*p)(char) = NULL;  // NOLINT
779   EXPECT_TRUE(HasPrefix(Print(p),
780                         Print(sizeof(p)) + "-byte object "));
781 }
782 
783 // Tests printing C arrays.
784 
785 // The difference between this and Print() is that it ensures that the
786 // argument is a reference to an array.
787 template <typename T, size_t N>
PrintArrayHelper(T (& a)[N])788 std::string PrintArrayHelper(T (&a)[N]) {
789   return Print(a);
790 }
791 
792 // One-dimensional array.
TEST(PrintArrayTest,OneDimensionalArray)793 TEST(PrintArrayTest, OneDimensionalArray) {
794   int a[5] = { 1, 2, 3, 4, 5 };
795   EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
796 }
797 
798 // Two-dimensional array.
TEST(PrintArrayTest,TwoDimensionalArray)799 TEST(PrintArrayTest, TwoDimensionalArray) {
800   int a[2][5] = {
801     { 1, 2, 3, 4, 5 },
802     { 6, 7, 8, 9, 0 }
803   };
804   EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
805 }
806 
807 // Array of const elements.
TEST(PrintArrayTest,ConstArray)808 TEST(PrintArrayTest, ConstArray) {
809   const bool a[1] = { false };
810   EXPECT_EQ("{ false }", PrintArrayHelper(a));
811 }
812 
813 // char array without terminating NUL.
TEST(PrintArrayTest,CharArrayWithNoTerminatingNul)814 TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {
815   // Array a contains '\0' in the middle and doesn't end with '\0'.
816   char a[] = { 'H', '\0', 'i' };
817   EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
818 }
819 
820 // char array with terminating NUL.
TEST(PrintArrayTest,CharArrayWithTerminatingNul)821 TEST(PrintArrayTest, CharArrayWithTerminatingNul) {
822   const char a[] = "\0Hi";
823   EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a));
824 }
825 
826 #ifdef __cpp_char8_t
827 // char_t array without terminating NUL.
TEST(PrintArrayTest,Char8ArrayWithNoTerminatingNul)828 TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) {
829   // Array a contains '\0' in the middle and doesn't end with '\0'.
830   const char8_t a[] = {u8'H', u8'\0', u8'i'};
831   EXPECT_EQ("u8\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
832 }
833 
834 // char8_t array with terminating NUL.
835 TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) {
836   const char8_t a[] = u8"\0世界";
837   EXPECT_EQ(
838       "u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
839       PrintArrayHelper(a));
840 }
841 #endif
842 
843 // const char16_t array without terminating NUL.
844 TEST(PrintArrayTest, Char16ArrayWithNoTerminatingNul) {
845   // Array a contains '\0' in the middle and doesn't end with '\0'.
846   const char16_t a[] = {u'こ', u'\0', u'ん', u'に', u'ち', u'は'};
847   EXPECT_EQ("u\"\\x3053\\0\\x3093\\x306B\\x3061\\x306F\" (no terminating NUL)",
848             PrintArrayHelper(a));
849 }
850 
851 // char16_t array with terminating NUL.
852 TEST(PrintArrayTest, Char16ArrayWithTerminatingNul) {
853   const char16_t a[] = u"\0こんにちは";
854   EXPECT_EQ("u\"\\0\\x3053\\x3093\\x306B\\x3061\\x306F\"", PrintArrayHelper(a));
855 }
856 
857 // char32_t array without terminating NUL.
858 TEST(PrintArrayTest, Char32ArrayWithNoTerminatingNul) {
859   // Array a contains '\0' in the middle and doesn't end with '\0'.
860   const char32_t a[] = {U'��', U'\0', U'��'};
861   EXPECT_EQ("U\"\\x1F44B\\0\\x1F30C\" (no terminating NUL)",
862             PrintArrayHelper(a));
863 }
864 
865 // char32_t array with terminating NUL.
866 TEST(PrintArrayTest, Char32ArrayWithTerminatingNul) {
867   const char32_t a[] = U"\0����";
868   EXPECT_EQ("U\"\\0\\x1F44B\\x1F30C\"", PrintArrayHelper(a));
869 }
870 
871 // wchar_t array without terminating NUL.
872 TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) {
873   // Array a contains '\0' in the middle and doesn't end with '\0'.
874   const wchar_t a[] = {L'H', L'\0', L'i'};
875   EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
876 }
877 
878 // wchar_t array with terminating NUL.
879 TEST(PrintArrayTest, WCharArrayWithTerminatingNul) {
880   const wchar_t a[] = L"\0Hi";
881   EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a));
882 }
883 
884 // Array of objects.
885 TEST(PrintArrayTest, ObjectArray) {
886   std::string a[3] = {"Hi", "Hello", "Ni hao"};
887   EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a));
888 }
889 
890 // Array with many elements.
891 TEST(PrintArrayTest, BigArray) {
892   int a[100] = { 1, 2, 3 };
893   EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }",
894             PrintArrayHelper(a));
895 }
896 
897 // Tests printing ::string and ::std::string.
898 
899 // ::std::string.
900 TEST(PrintStringTest, StringInStdNamespace) {
901   const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
902   const ::std::string str(s, sizeof(s));
903   EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
904             Print(str));
905 }
906 
907 TEST(PrintStringTest, StringAmbiguousHex) {
908   // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of:
909   // '\x6', '\x6B', or '\x6BA'.
910 
911   // a hex escaping sequence following by a decimal digit
912   EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3")));
913   // a hex escaping sequence following by a hex digit (lower-case)
914   EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas")));
915   // a hex escaping sequence following by a hex digit (upper-case)
916   EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA")));
917   // a hex escaping sequence following by a non-xdigit
918   EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
919 }
920 
921 // Tests printing ::std::wstring.
922 #if GTEST_HAS_STD_WSTRING
923 // ::std::wstring.
924 TEST(PrintWideStringTest, StringInStdNamespace) {
925   const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
926   const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t));
927   EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
928             "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
929             Print(str));
930 }
931 
932 TEST(PrintWideStringTest, StringAmbiguousHex) {
933   // same for wide strings.
934   EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3")));
935   EXPECT_EQ("L\"mm\\x6\" L\"bananas\"",
936             Print(::std::wstring(L"mm\x6" L"bananas")));
937   EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"",
938             Print(::std::wstring(L"NOM\x6" L"BANANA")));
939   EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
940 }
941 #endif  // GTEST_HAS_STD_WSTRING
942 
943 #ifdef __cpp_char8_t
944 TEST(PrintStringTest, U8String) {
945   std::u8string str = u8"Hello, 世界";
946   EXPECT_EQ(str, str);  // Verify EXPECT_EQ compiles with this type.
947   EXPECT_EQ("u8\"Hello, \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", Print(str));
948 }
949 #endif
950 
951 TEST(PrintStringTest, U16String) {
952   std::u16string str = u"Hello, 世界";
953   EXPECT_EQ(str, str);  // Verify EXPECT_EQ compiles with this type.
954   EXPECT_EQ("u\"Hello, \\x4E16\\x754C\"", Print(str));
955 }
956 
957 TEST(PrintStringTest, U32String) {
958   std::u32string str = U"Hello, ��️";
959   EXPECT_EQ(str, str);  // Verify EXPECT_EQ compiles with this type
960   EXPECT_EQ("U\"Hello, \\x1F5FA\\xFE0F\"", Print(str));
961 }
962 
963 // Tests printing types that support generic streaming (i.e. streaming
964 // to std::basic_ostream<Char, CharTraits> for any valid Char and
965 // CharTraits types).
966 
967 // Tests printing a non-template type that supports generic streaming.
968 
969 class AllowsGenericStreaming {};
970 
971 template <typename Char, typename CharTraits>
972 std::basic_ostream<Char, CharTraits>& operator<<(
973     std::basic_ostream<Char, CharTraits>& os,
974     const AllowsGenericStreaming& /* a */) {
975   return os << "AllowsGenericStreaming";
976 }
977 
978 TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) {
979   AllowsGenericStreaming a;
980   EXPECT_EQ("AllowsGenericStreaming", Print(a));
981 }
982 
983 // Tests printing a template type that supports generic streaming.
984 
985 template <typename T>
986 class AllowsGenericStreamingTemplate {};
987 
988 template <typename Char, typename CharTraits, typename T>
989 std::basic_ostream<Char, CharTraits>& operator<<(
990     std::basic_ostream<Char, CharTraits>& os,
991     const AllowsGenericStreamingTemplate<T>& /* a */) {
992   return os << "AllowsGenericStreamingTemplate";
993 }
994 
995 TEST(PrintTypeWithGenericStreamingTest, TemplateType) {
996   AllowsGenericStreamingTemplate<int> a;
997   EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a));
998 }
999 
1000 // Tests printing a type that supports generic streaming and can be
1001 // implicitly converted to another printable type.
1002 
1003 template <typename T>
1004 class AllowsGenericStreamingAndImplicitConversionTemplate {
1005  public:
operator bool() const1006   operator bool() const { return false; }
1007 };
1008 
1009 template <typename Char, typename CharTraits, typename T>
1010 std::basic_ostream<Char, CharTraits>& operator<<(
1011     std::basic_ostream<Char, CharTraits>& os,
1012     const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) {
1013   return os << "AllowsGenericStreamingAndImplicitConversionTemplate";
1014 }
1015 
1016 TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
1017   AllowsGenericStreamingAndImplicitConversionTemplate<int> a;
1018   EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
1019 }
1020 
1021 #if GTEST_INTERNAL_HAS_STRING_VIEW
1022 
1023 // Tests printing internal::StringView.
1024 
1025 TEST(PrintStringViewTest, SimpleStringView) {
1026   const internal::StringView sp = "Hello";
1027   EXPECT_EQ("\"Hello\"", Print(sp));
1028 }
1029 
1030 TEST(PrintStringViewTest, UnprintableCharacters) {
1031   const char str[] = "NUL (\0) and \r\t";
1032   const internal::StringView sp(str, sizeof(str) - 1);
1033   EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
1034 }
1035 
1036 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1037 
1038 // Tests printing STL containers.
1039 
1040 TEST(PrintStlContainerTest, EmptyDeque) {
1041   deque<char> empty;
1042   EXPECT_EQ("{}", Print(empty));
1043 }
1044 
1045 TEST(PrintStlContainerTest, NonEmptyDeque) {
1046   deque<int> non_empty;
1047   non_empty.push_back(1);
1048   non_empty.push_back(3);
1049   EXPECT_EQ("{ 1, 3 }", Print(non_empty));
1050 }
1051 
1052 
1053 TEST(PrintStlContainerTest, OneElementHashMap) {
1054   ::std::unordered_map<int, char> map1;
1055   map1[1] = 'a';
1056   EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1));
1057 }
1058 
1059 TEST(PrintStlContainerTest, HashMultiMap) {
1060   ::std::unordered_multimap<int, bool> map1;
1061   map1.insert(make_pair(5, true));
1062   map1.insert(make_pair(5, false));
1063 
1064   // Elements of hash_multimap can be printed in any order.
1065   const std::string result = Print(map1);
1066   EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
1067               result == "{ (5, false), (5, true) }")
1068                   << " where Print(map1) returns \"" << result << "\".";
1069 }
1070 
1071 
1072 
1073 TEST(PrintStlContainerTest, HashSet) {
1074   ::std::unordered_set<int> set1;
1075   set1.insert(1);
1076   EXPECT_EQ("{ 1 }", Print(set1));
1077 }
1078 
1079 TEST(PrintStlContainerTest, HashMultiSet) {
1080   const int kSize = 5;
1081   int a[kSize] = { 1, 1, 2, 5, 1 };
1082   ::std::unordered_multiset<int> set1(a, a + kSize);
1083 
1084   // Elements of hash_multiset can be printed in any order.
1085   const std::string result = Print(set1);
1086   const std::string expected_pattern = "{ d, d, d, d, d }";  // d means a digit.
1087 
1088   // Verifies the result matches the expected pattern; also extracts
1089   // the numbers in the result.
1090   ASSERT_EQ(expected_pattern.length(), result.length());
1091   std::vector<int> numbers;
1092   for (size_t i = 0; i != result.length(); i++) {
1093     if (expected_pattern[i] == 'd') {
1094       ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
1095       numbers.push_back(result[i] - '0');
1096     } else {
1097       EXPECT_EQ(expected_pattern[i], result[i]) << " where result is "
1098                                                 << result;
1099     }
1100   }
1101 
1102   // Makes sure the result contains the right numbers.
1103   std::sort(numbers.begin(), numbers.end());
1104   std::sort(a, a + kSize);
1105   EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
1106 }
1107 
1108 
1109 TEST(PrintStlContainerTest, List) {
1110   const std::string a[] = {"hello", "world"};
1111   const list<std::string> strings(a, a + 2);
1112   EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings));
1113 }
1114 
1115 TEST(PrintStlContainerTest, Map) {
1116   map<int, bool> map1;
1117   map1[1] = true;
1118   map1[5] = false;
1119   map1[3] = true;
1120   EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1));
1121 }
1122 
1123 TEST(PrintStlContainerTest, MultiMap) {
1124   multimap<bool, int> map1;
1125   // The make_pair template function would deduce the type as
1126   // pair<bool, int> here, and since the key part in a multimap has to
1127   // be constant, without a templated ctor in the pair class (as in
1128   // libCstd on Solaris), make_pair call would fail to compile as no
1129   // implicit conversion is found.  Thus explicit typename is used
1130   // here instead.
1131   map1.insert(pair<const bool, int>(true, 0));
1132   map1.insert(pair<const bool, int>(true, 1));
1133   map1.insert(pair<const bool, int>(false, 2));
1134   EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1));
1135 }
1136 
1137 TEST(PrintStlContainerTest, Set) {
1138   const unsigned int a[] = { 3, 0, 5 };
1139   set<unsigned int> set1(a, a + 3);
1140   EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
1141 }
1142 
1143 TEST(PrintStlContainerTest, MultiSet) {
1144   const int a[] = { 1, 1, 2, 5, 1 };
1145   multiset<int> set1(a, a + 5);
1146   EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
1147 }
1148 
1149 
1150 TEST(PrintStlContainerTest, SinglyLinkedList) {
1151   int a[] = { 9, 2, 8 };
1152   const std::forward_list<int> ints(a, a + 3);
1153   EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
1154 }
1155 
1156 TEST(PrintStlContainerTest, Pair) {
1157   pair<const bool, int> p(true, 5);
1158   EXPECT_EQ("(true, 5)", Print(p));
1159 }
1160 
1161 TEST(PrintStlContainerTest, Vector) {
1162   vector<int> v;
1163   v.push_back(1);
1164   v.push_back(2);
1165   EXPECT_EQ("{ 1, 2 }", Print(v));
1166 }
1167 
1168 TEST(PrintStlContainerTest, LongSequence) {
1169   const int a[100] = { 1, 2, 3 };
1170   const vector<int> v(a, a + 100);
1171   EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
1172             "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v));
1173 }
1174 
1175 TEST(PrintStlContainerTest, NestedContainer) {
1176   const int a1[] = { 1, 2 };
1177   const int a2[] = { 3, 4, 5 };
1178   const list<int> l1(a1, a1 + 2);
1179   const list<int> l2(a2, a2 + 3);
1180 
1181   vector<list<int> > v;
1182   v.push_back(l1);
1183   v.push_back(l2);
1184   EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
1185 }
1186 
1187 TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
1188   const int a[3] = { 1, 2, 3 };
1189   NativeArray<int> b(a, 3, RelationToSourceReference());
1190   EXPECT_EQ("{ 1, 2, 3 }", Print(b));
1191 }
1192 
1193 TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
1194   const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
1195   NativeArray<int[3]> b(a, 2, RelationToSourceReference());
1196   EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
1197 }
1198 
1199 // Tests that a class named iterator isn't treated as a container.
1200 
1201 struct iterator {
1202   char x;
1203 };
1204 
1205 TEST(PrintStlContainerTest, Iterator) {
1206   iterator it = {};
1207   EXPECT_EQ("1-byte object <00>", Print(it));
1208 }
1209 
1210 // Tests that a class named const_iterator isn't treated as a container.
1211 
1212 struct const_iterator {
1213   char x;
1214 };
1215 
1216 TEST(PrintStlContainerTest, ConstIterator) {
1217   const_iterator it = {};
1218   EXPECT_EQ("1-byte object <00>", Print(it));
1219 }
1220 
1221 // Tests printing ::std::tuples.
1222 
1223 // Tuples of various arities.
1224 TEST(PrintStdTupleTest, VariousSizes) {
1225   ::std::tuple<> t0;
1226   EXPECT_EQ("()", Print(t0));
1227 
1228   ::std::tuple<int> t1(5);
1229   EXPECT_EQ("(5)", Print(t1));
1230 
1231   ::std::tuple<char, bool> t2('a', true);
1232   EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
1233 
1234   ::std::tuple<bool, int, int> t3(false, 2, 3);
1235   EXPECT_EQ("(false, 2, 3)", Print(t3));
1236 
1237   ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4);
1238   EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
1239 
1240   const char* const str = "8";
1241   ::std::tuple<bool, char, short, int32_t, int64_t, float, double,  // NOLINT
1242                const char*, void*, std::string>
1243       t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str,  // NOLINT
1244           nullptr, "10");
1245   EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
1246             " pointing to \"8\", NULL, \"10\")",
1247             Print(t10));
1248 }
1249 
1250 // Nested tuples.
1251 TEST(PrintStdTupleTest, NestedTuple) {
1252   ::std::tuple< ::std::tuple<int, bool>, char> nested(
1253       ::std::make_tuple(5, true), 'a');
1254   EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
1255 }
1256 
1257 TEST(PrintNullptrT, Basic) {
1258   EXPECT_EQ("(nullptr)", Print(nullptr));
1259 }
1260 
1261 TEST(PrintReferenceWrapper, Printable) {
1262   int x = 5;
1263   EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::ref(x)));
1264   EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::cref(x)));
1265 }
1266 
1267 TEST(PrintReferenceWrapper, Unprintable) {
1268   ::foo::UnprintableInFoo up;
1269   EXPECT_EQ(
1270       "@" + PrintPointer(&up) +
1271           " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1272       Print(std::ref(up)));
1273   EXPECT_EQ(
1274       "@" + PrintPointer(&up) +
1275           " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1276       Print(std::cref(up)));
1277 }
1278 
1279 // Tests printing user-defined unprintable types.
1280 
1281 // Unprintable types in the global namespace.
1282 TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
1283   EXPECT_EQ("1-byte object <00>",
1284             Print(UnprintableTemplateInGlobal<char>()));
1285 }
1286 
1287 // Unprintable types in a user namespace.
1288 TEST(PrintUnprintableTypeTest, InUserNamespace) {
1289   EXPECT_EQ("16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1290             Print(::foo::UnprintableInFoo()));
1291 }
1292 
1293 // Unprintable types are that too big to be printed completely.
1294 
1295 struct Big {
Bigtesting::gtest_printers_test::TEST::Big1296   Big() { memset(array, 0, sizeof(array)); }
1297   char array[257];
1298 };
1299 
1300 TEST(PrintUnpritableTypeTest, BigObject) {
1301   EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
1302             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1303             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1304             "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
1305             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1306             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1307             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
1308             Print(Big()));
1309 }
1310 
1311 // Tests printing user-defined streamable types.
1312 
1313 // Streamable types in the global namespace.
1314 TEST(PrintStreamableTypeTest, InGlobalNamespace) {
1315   StreamableInGlobal x;
1316   EXPECT_EQ("StreamableInGlobal", Print(x));
1317   EXPECT_EQ("StreamableInGlobal*", Print(&x));
1318 }
1319 
1320 // Printable template types in a user namespace.
1321 TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
1322   EXPECT_EQ("StreamableTemplateInFoo: 0",
1323             Print(::foo::StreamableTemplateInFoo<int>()));
1324 }
1325 
1326 TEST(PrintStreamableTypeTest, TypeInUserNamespaceWithTemplatedStreamOperator) {
1327   EXPECT_EQ("TemplatedStreamableInFoo",
1328             Print(::foo::TemplatedStreamableInFoo()));
1329 }
1330 
1331 TEST(PrintStreamableTypeTest, SubclassUsesSuperclassStreamOperator) {
1332   ParentClass parent;
1333   ChildClassWithStreamOperator child_stream;
1334   ChildClassWithoutStreamOperator child_no_stream;
1335   EXPECT_EQ("ParentClass", Print(parent));
1336   EXPECT_EQ("ChildClassWithStreamOperator", Print(child_stream));
1337   EXPECT_EQ("ParentClass", Print(child_no_stream));
1338 }
1339 
1340 // Tests printing a user-defined recursive container type that has a <<
1341 // operator.
1342 TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
1343   ::foo::PathLike x;
1344   EXPECT_EQ("Streamable-PathLike", Print(x));
1345   const ::foo::PathLike cx;
1346   EXPECT_EQ("Streamable-PathLike", Print(cx));
1347 }
1348 
1349 // Tests printing user-defined types that have a PrintTo() function.
1350 TEST(PrintPrintableTypeTest, InUserNamespace) {
1351   EXPECT_EQ("PrintableViaPrintTo: 0",
1352             Print(::foo::PrintableViaPrintTo()));
1353 }
1354 
1355 // Tests printing a pointer to a user-defined type that has a <<
1356 // operator for its pointer.
1357 TEST(PrintPrintableTypeTest, PointerInUserNamespace) {
1358   ::foo::PointerPrintable x;
1359   EXPECT_EQ("PointerPrintable*", Print(&x));
1360 }
1361 
1362 // Tests printing user-defined class template that have a PrintTo() function.
1363 TEST(PrintPrintableTypeTest, TemplateInUserNamespace) {
1364   EXPECT_EQ("PrintableViaPrintToTemplate: 5",
1365             Print(::foo::PrintableViaPrintToTemplate<int>(5)));
1366 }
1367 
1368 // Tests that the universal printer prints both the address and the
1369 // value of a reference.
1370 TEST(PrintReferenceTest, PrintsAddressAndValue) {
1371   int n = 5;
1372   EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
1373 
1374   int a[2][3] = {
1375     { 0, 1, 2 },
1376     { 3, 4, 5 }
1377   };
1378   EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
1379             PrintByRef(a));
1380 
1381   const ::foo::UnprintableInFoo x;
1382   EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object "
1383             "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1384             PrintByRef(x));
1385 }
1386 
1387 // Tests that the universal printer prints a function pointer passed by
1388 // reference.
1389 TEST(PrintReferenceTest, HandlesFunctionPointer) {
1390   void (*fp)(int n) = &MyFunction;
1391   const std::string fp_pointer_string =
1392       PrintPointer(reinterpret_cast<const void*>(&fp));
1393   // We cannot directly cast &MyFunction to const void* because the
1394   // standard disallows casting between pointers to functions and
1395   // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
1396   // this limitation.
1397   const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(
1398       reinterpret_cast<internal::BiggestInt>(fp)));
1399   EXPECT_EQ("@" + fp_pointer_string + " " + fp_string,
1400             PrintByRef(fp));
1401 }
1402 
1403 // Tests that the universal printer prints a member function pointer
1404 // passed by reference.
1405 TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
1406   int (Foo::*p)(char ch) = &Foo::MyMethod;
1407   EXPECT_TRUE(HasPrefix(
1408       PrintByRef(p),
1409       "@" + PrintPointer(reinterpret_cast<const void*>(&p)) + " " +
1410           Print(sizeof(p)) + "-byte object "));
1411 
1412   char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
1413   EXPECT_TRUE(HasPrefix(
1414       PrintByRef(p2),
1415       "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) + " " +
1416           Print(sizeof(p2)) + "-byte object "));
1417 }
1418 
1419 // Tests that the universal printer prints a member variable pointer
1420 // passed by reference.
1421 TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
1422   int Foo::*p = &Foo::value;  // NOLINT
1423   EXPECT_TRUE(HasPrefix(
1424       PrintByRef(p),
1425       "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object "));
1426 }
1427 
1428 // Tests that FormatForComparisonFailureMessage(), which is used to print
1429 // an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion
1430 // fails, formats the operand in the desired way.
1431 
1432 // scalar
1433 TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
1434   EXPECT_STREQ("123",
1435                FormatForComparisonFailureMessage(123, 124).c_str());
1436 }
1437 
1438 // non-char pointer
1439 TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {
1440   int n = 0;
1441   EXPECT_EQ(PrintPointer(&n),
1442             FormatForComparisonFailureMessage(&n, &n).c_str());
1443 }
1444 
1445 // non-char array
1446 TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
1447   // In expression 'array == x', 'array' is compared by pointer.
1448   // Therefore we want to print an array operand as a pointer.
1449   int n[] = { 1, 2, 3 };
1450   EXPECT_EQ(PrintPointer(n),
1451             FormatForComparisonFailureMessage(n, n).c_str());
1452 }
1453 
1454 // Tests formatting a char pointer when it's compared with another pointer.
1455 // In this case we want to print it as a raw pointer, as the comparison is by
1456 // pointer.
1457 
1458 // char pointer vs pointer
1459 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
1460   // In expression 'p == x', where 'p' and 'x' are (const or not) char
1461   // pointers, the operands are compared by pointer.  Therefore we
1462   // want to print 'p' as a pointer instead of a C string (we don't
1463   // even know if it's supposed to point to a valid C string).
1464 
1465   // const char*
1466   const char* s = "hello";
1467   EXPECT_EQ(PrintPointer(s),
1468             FormatForComparisonFailureMessage(s, s).c_str());
1469 
1470   // char*
1471   char ch = 'a';
1472   EXPECT_EQ(PrintPointer(&ch),
1473             FormatForComparisonFailureMessage(&ch, &ch).c_str());
1474 }
1475 
1476 // wchar_t pointer vs pointer
1477 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
1478   // In expression 'p == x', where 'p' and 'x' are (const or not) char
1479   // pointers, the operands are compared by pointer.  Therefore we
1480   // want to print 'p' as a pointer instead of a wide C string (we don't
1481   // even know if it's supposed to point to a valid wide C string).
1482 
1483   // const wchar_t*
1484   const wchar_t* s = L"hello";
1485   EXPECT_EQ(PrintPointer(s),
1486             FormatForComparisonFailureMessage(s, s).c_str());
1487 
1488   // wchar_t*
1489   wchar_t ch = L'a';
1490   EXPECT_EQ(PrintPointer(&ch),
1491             FormatForComparisonFailureMessage(&ch, &ch).c_str());
1492 }
1493 
1494 // Tests formatting a char pointer when it's compared to a string object.
1495 // In this case we want to print the char pointer as a C string.
1496 
1497 // char pointer vs std::string
1498 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) {
1499   const char* s = "hello \"world";
1500   EXPECT_STREQ("\"hello \\\"world\"",  // The string content should be escaped.
1501                FormatForComparisonFailureMessage(s, ::std::string()).c_str());
1502 
1503   // char*
1504   char str[] = "hi\1";
1505   char* p = str;
1506   EXPECT_STREQ("\"hi\\x1\"",  // The string content should be escaped.
1507                FormatForComparisonFailureMessage(p, ::std::string()).c_str());
1508 }
1509 
1510 #if GTEST_HAS_STD_WSTRING
1511 // wchar_t pointer vs std::wstring
1512 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) {
1513   const wchar_t* s = L"hi \"world";
1514   EXPECT_STREQ("L\"hi \\\"world\"",  // The string content should be escaped.
1515                FormatForComparisonFailureMessage(s, ::std::wstring()).c_str());
1516 
1517   // wchar_t*
1518   wchar_t str[] = L"hi\1";
1519   wchar_t* p = str;
1520   EXPECT_STREQ("L\"hi\\x1\"",  // The string content should be escaped.
1521                FormatForComparisonFailureMessage(p, ::std::wstring()).c_str());
1522 }
1523 #endif
1524 
1525 // Tests formatting a char array when it's compared with a pointer or array.
1526 // In this case we want to print the array as a row pointer, as the comparison
1527 // is by pointer.
1528 
1529 // char array vs pointer
1530 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) {
1531   char str[] = "hi \"world\"";
1532   char* p = nullptr;
1533   EXPECT_EQ(PrintPointer(str),
1534             FormatForComparisonFailureMessage(str, p).c_str());
1535 }
1536 
1537 // char array vs char array
1538 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) {
1539   const char str[] = "hi \"world\"";
1540   EXPECT_EQ(PrintPointer(str),
1541             FormatForComparisonFailureMessage(str, str).c_str());
1542 }
1543 
1544 // wchar_t array vs pointer
1545 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) {
1546   wchar_t str[] = L"hi \"world\"";
1547   wchar_t* p = nullptr;
1548   EXPECT_EQ(PrintPointer(str),
1549             FormatForComparisonFailureMessage(str, p).c_str());
1550 }
1551 
1552 // wchar_t array vs wchar_t array
1553 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) {
1554   const wchar_t str[] = L"hi \"world\"";
1555   EXPECT_EQ(PrintPointer(str),
1556             FormatForComparisonFailureMessage(str, str).c_str());
1557 }
1558 
1559 // Tests formatting a char array when it's compared with a string object.
1560 // In this case we want to print the array as a C string.
1561 
1562 // char array vs std::string
1563 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) {
1564   const char str[] = "hi \"world\"";
1565   EXPECT_STREQ("\"hi \\\"world\\\"\"",  // The content should be escaped.
1566                FormatForComparisonFailureMessage(str, ::std::string()).c_str());
1567 }
1568 
1569 #if GTEST_HAS_STD_WSTRING
1570 // wchar_t array vs std::wstring
1571 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
1572   const wchar_t str[] = L"hi \"w\0rld\"";
1573   EXPECT_STREQ(
1574       "L\"hi \\\"w\"",  // The content should be escaped.
1575                         // Embedded NUL terminates the string.
1576       FormatForComparisonFailureMessage(str, ::std::wstring()).c_str());
1577 }
1578 #endif
1579 
1580 // Useful for testing PrintToString().  We cannot use EXPECT_EQ()
1581 // there as its implementation uses PrintToString().  The caller must
1582 // ensure that 'value' has no side effect.
1583 #define EXPECT_PRINT_TO_STRING_(value, expected_string)         \
1584   EXPECT_TRUE(PrintToString(value) == (expected_string))        \
1585       << " where " #value " prints as " << (PrintToString(value))
1586 
1587 TEST(PrintToStringTest, WorksForScalar) {
1588   EXPECT_PRINT_TO_STRING_(123, "123");
1589 }
1590 
1591 TEST(PrintToStringTest, WorksForPointerToConstChar) {
1592   const char* p = "hello";
1593   EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1594 }
1595 
1596 TEST(PrintToStringTest, WorksForPointerToNonConstChar) {
1597   char s[] = "hello";
1598   char* p = s;
1599   EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1600 }
1601 
1602 TEST(PrintToStringTest, EscapesForPointerToConstChar) {
1603   const char* p = "hello\n";
1604   EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\"");
1605 }
1606 
1607 TEST(PrintToStringTest, EscapesForPointerToNonConstChar) {
1608   char s[] = "hello\1";
1609   char* p = s;
1610   EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\"");
1611 }
1612 
1613 TEST(PrintToStringTest, WorksForArray) {
1614   int n[3] = { 1, 2, 3 };
1615   EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }");
1616 }
1617 
1618 TEST(PrintToStringTest, WorksForCharArray) {
1619   char s[] = "hello";
1620   EXPECT_PRINT_TO_STRING_(s, "\"hello\"");
1621 }
1622 
1623 TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {
1624   const char str_with_nul[] = "hello\0 world";
1625   EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\"");
1626 
1627   char mutable_str_with_nul[] = "hello\0 world";
1628   EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\"");
1629 }
1630 
1631   TEST(PrintToStringTest, ContainsNonLatin) {
1632   // Sanity test with valid UTF-8. Prints both in hex and as text.
1633   std::string non_ascii_str = ::std::string("오전 4:30");
1634   EXPECT_PRINT_TO_STRING_(non_ascii_str,
1635                           "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n"
1636                           "    As Text: \"오전 4:30\"");
1637   non_ascii_str = ::std::string("From ä — ẑ");
1638   EXPECT_PRINT_TO_STRING_(non_ascii_str,
1639                           "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\""
1640                           "\n    As Text: \"From ä — ẑ\"");
1641 }
1642 
1643 TEST(IsValidUTF8Test, IllFormedUTF8) {
1644   // The following test strings are ill-formed UTF-8 and are printed
1645   // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is
1646   // expected to fail, thus output does not contain "As Text:".
1647 
1648   static const char *const kTestdata[][2] = {
1649     // 2-byte lead byte followed by a single-byte character.
1650     {"\xC3\x74", "\"\\xC3t\""},
1651     // Valid 2-byte character followed by an orphan trail byte.
1652     {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""},
1653     // Lead byte without trail byte.
1654     {"abc\xC3", "\"abc\\xC3\""},
1655     // 3-byte lead byte, single-byte character, orphan trail byte.
1656     {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""},
1657     // Truncated 3-byte character.
1658     {"\xE2\x80", "\"\\xE2\\x80\""},
1659     // Truncated 3-byte character followed by valid 2-byte char.
1660     {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""},
1661     // Truncated 3-byte character followed by a single-byte character.
1662     {"\xE2\x80\x7A", "\"\\xE2\\x80z\""},
1663     // 3-byte lead byte followed by valid 3-byte character.
1664     {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""},
1665     // 4-byte lead byte followed by valid 3-byte character.
1666     {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""},
1667     // Truncated 4-byte character.
1668     {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""},
1669      // Invalid UTF-8 byte sequences embedded in other chars.
1670     {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""},
1671     {"abc\xC3\x84\xE2\x80\xC3\x84xyz",
1672      "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""},
1673     // Non-shortest UTF-8 byte sequences are also ill-formed.
1674     // The classics: xC0, xC1 lead byte.
1675     {"\xC0\x80", "\"\\xC0\\x80\""},
1676     {"\xC1\x81", "\"\\xC1\\x81\""},
1677     // Non-shortest sequences.
1678     {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
1679     {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
1680     // Last valid code point before surrogate range, should be printed as text,
1681     // too.
1682     {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n    As Text: \"퟿\""},
1683     // Start of surrogate lead. Surrogates are not printed as text.
1684     {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""},
1685     // Last non-private surrogate lead.
1686     {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""},
1687     // First private-use surrogate lead.
1688     {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""},
1689     // Last private-use surrogate lead.
1690     {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
1691     // Mid-point of surrogate trail.
1692     {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
1693     // First valid code point after surrogate range, should be printed as text,
1694     // too.
1695     {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n    As Text: \"\""}
1696   };
1697 
1698   for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) {
1699     EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
1700   }
1701 }
1702 
1703 #undef EXPECT_PRINT_TO_STRING_
1704 
1705 TEST(UniversalTersePrintTest, WorksForNonReference) {
1706   ::std::stringstream ss;
1707   UniversalTersePrint(123, &ss);
1708   EXPECT_EQ("123", ss.str());
1709 }
1710 
1711 TEST(UniversalTersePrintTest, WorksForReference) {
1712   const int& n = 123;
1713   ::std::stringstream ss;
1714   UniversalTersePrint(n, &ss);
1715   EXPECT_EQ("123", ss.str());
1716 }
1717 
1718 TEST(UniversalTersePrintTest, WorksForCString) {
1719   const char* s1 = "abc";
1720   ::std::stringstream ss1;
1721   UniversalTersePrint(s1, &ss1);
1722   EXPECT_EQ("\"abc\"", ss1.str());
1723 
1724   char* s2 = const_cast<char*>(s1);
1725   ::std::stringstream ss2;
1726   UniversalTersePrint(s2, &ss2);
1727   EXPECT_EQ("\"abc\"", ss2.str());
1728 
1729   const char* s3 = nullptr;
1730   ::std::stringstream ss3;
1731   UniversalTersePrint(s3, &ss3);
1732   EXPECT_EQ("NULL", ss3.str());
1733 }
1734 
1735 TEST(UniversalPrintTest, WorksForNonReference) {
1736   ::std::stringstream ss;
1737   UniversalPrint(123, &ss);
1738   EXPECT_EQ("123", ss.str());
1739 }
1740 
1741 TEST(UniversalPrintTest, WorksForReference) {
1742   const int& n = 123;
1743   ::std::stringstream ss;
1744   UniversalPrint(n, &ss);
1745   EXPECT_EQ("123", ss.str());
1746 }
1747 
1748 TEST(UniversalPrintTest, WorksForPairWithConst) {
1749   std::pair<const Wrapper<std::string>, int> p(Wrapper<std::string>("abc"), 1);
1750   ::std::stringstream ss;
1751   UniversalPrint(p, &ss);
1752   EXPECT_EQ("(Wrapper(\"abc\"), 1)", ss.str());
1753 }
1754 
1755 TEST(UniversalPrintTest, WorksForCString) {
1756   const char* s1 = "abc";
1757   ::std::stringstream ss1;
1758   UniversalPrint(s1, &ss1);
1759   EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str()));
1760 
1761   char* s2 = const_cast<char*>(s1);
1762   ::std::stringstream ss2;
1763   UniversalPrint(s2, &ss2);
1764   EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str()));
1765 
1766   const char* s3 = nullptr;
1767   ::std::stringstream ss3;
1768   UniversalPrint(s3, &ss3);
1769   EXPECT_EQ("NULL", ss3.str());
1770 }
1771 
1772 TEST(UniversalPrintTest, WorksForCharArray) {
1773   const char str[] = "\"Line\0 1\"\nLine 2";
1774   ::std::stringstream ss1;
1775   UniversalPrint(str, &ss1);
1776   EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str());
1777 
1778   const char mutable_str[] = "\"Line\0 1\"\nLine 2";
1779   ::std::stringstream ss2;
1780   UniversalPrint(mutable_str, &ss2);
1781   EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str());
1782 }
1783 
1784 TEST(UniversalPrintTest, IncompleteType) {
1785   struct Incomplete;
1786   char some_object = 0;
1787   EXPECT_EQ("(incomplete type)",
1788             PrintToString(reinterpret_cast<Incomplete&>(some_object)));
1789 }
1790 
1791 TEST(UniversalPrintTest, SmartPointers) {
1792   EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
1793   std::unique_ptr<int> p(new int(17));
1794   EXPECT_EQ("(ptr = " + PrintPointer(p.get()) + ", value = 17)",
1795             PrintToString(p));
1796   std::unique_ptr<int[]> p2(new int[2]);
1797   EXPECT_EQ("(" + PrintPointer(p2.get()) + ")", PrintToString(p2));
1798 
1799   EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
1800   std::shared_ptr<int> p3(new int(1979));
1801   EXPECT_EQ("(ptr = " + PrintPointer(p3.get()) + ", value = 1979)",
1802             PrintToString(p3));
1803 #if __cpp_lib_shared_ptr_arrays >= 201611L
1804   std::shared_ptr<int[]> p4(new int[2]);
1805   EXPECT_EQ("(" + PrintPointer(p4.get()) + ")", PrintToString(p4));
1806 #endif
1807 
1808   // modifiers
1809   EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
1810   EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int>()));
1811   EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int>()));
1812   EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile const int>()));
1813   EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int[]>()));
1814   EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int[]>()));
1815   EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int[]>()));
1816   EXPECT_EQ("(nullptr)",
1817             PrintToString(std::unique_ptr<volatile const int[]>()));
1818   EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
1819   EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int>()));
1820   EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int>()));
1821   EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile const int>()));
1822 #if __cpp_lib_shared_ptr_arrays >= 201611L
1823   EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int[]>()));
1824   EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int[]>()));
1825   EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int[]>()));
1826   EXPECT_EQ("(nullptr)",
1827             PrintToString(std::shared_ptr<volatile const int[]>()));
1828 #endif
1829 
1830   // void
1831   EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<void, void (*)(void*)>(
1832                              nullptr, nullptr)));
1833   EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
1834             PrintToString(
__anon61a3771f0602(void*) 1835                 std::unique_ptr<void, void (*)(void*)>(p.get(), [](void*) {})));
1836   EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<void>()));
1837   EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
__anon61a3771f0702(void*) 1838             PrintToString(std::shared_ptr<void>(p.get(), [](void*) {})));
1839 }
1840 
1841 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
1842   Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
1843   EXPECT_EQ(0u, result.size());
1844 }
1845 
1846 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
1847   Strings result = UniversalTersePrintTupleFieldsToStrings(
1848       ::std::make_tuple(1));
1849   ASSERT_EQ(1u, result.size());
1850   EXPECT_EQ("1", result[0]);
1851 }
1852 
1853 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
1854   Strings result = UniversalTersePrintTupleFieldsToStrings(
1855       ::std::make_tuple(1, 'a'));
1856   ASSERT_EQ(2u, result.size());
1857   EXPECT_EQ("1", result[0]);
1858   EXPECT_EQ("'a' (97, 0x61)", result[1]);
1859 }
1860 
1861 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
1862   const int n = 1;
1863   Strings result = UniversalTersePrintTupleFieldsToStrings(
1864       ::std::tuple<const int&, const char*>(n, "a"));
1865   ASSERT_EQ(2u, result.size());
1866   EXPECT_EQ("1", result[0]);
1867   EXPECT_EQ("\"a\"", result[1]);
1868 }
1869 
1870 #if GTEST_INTERNAL_HAS_ANY
1871 class PrintAnyTest : public ::testing::Test {
1872  protected:
1873   template <typename T>
ExpectedTypeName()1874   static std::string ExpectedTypeName() {
1875 #if GTEST_HAS_RTTI
1876     return internal::GetTypeName<T>();
1877 #else
1878     return "<unknown_type>";
1879 #endif  // GTEST_HAS_RTTI
1880   }
1881 };
1882 
1883 TEST_F(PrintAnyTest, Empty) {
1884   internal::Any any;
1885   EXPECT_EQ("no value", PrintToString(any));
1886 }
1887 
1888 TEST_F(PrintAnyTest, NonEmpty) {
1889   internal::Any any;
1890   constexpr int val1 = 10;
1891   const std::string val2 = "content";
1892 
1893   any = val1;
1894   EXPECT_EQ("value of type " + ExpectedTypeName<int>(), PrintToString(any));
1895 
1896   any = val2;
1897   EXPECT_EQ("value of type " + ExpectedTypeName<std::string>(),
1898             PrintToString(any));
1899 }
1900 #endif  // GTEST_INTERNAL_HAS_ANY
1901 
1902 #if GTEST_INTERNAL_HAS_OPTIONAL
1903 TEST(PrintOptionalTest, Basic) {
1904   EXPECT_EQ("(nullopt)", PrintToString(internal::Nullopt()));
1905   internal::Optional<int> value;
1906   EXPECT_EQ("(nullopt)", PrintToString(value));
1907   value = {7};
1908   EXPECT_EQ("(7)", PrintToString(value));
1909   EXPECT_EQ("(1.1)", PrintToString(internal::Optional<double>{1.1}));
1910   EXPECT_EQ("(\"A\")", PrintToString(internal::Optional<std::string>{"A"}));
1911 }
1912 #endif  // GTEST_INTERNAL_HAS_OPTIONAL
1913 
1914 #if GTEST_INTERNAL_HAS_VARIANT
1915 struct NonPrintable {
1916   unsigned char contents = 17;
1917 };
1918 
1919 TEST(PrintOneofTest, Basic) {
1920   using Type = internal::Variant<int, StreamableInGlobal, NonPrintable>;
1921   EXPECT_EQ("('int(index = 0)' with value 7)", PrintToString(Type(7)));
1922   EXPECT_EQ("('StreamableInGlobal(index = 1)' with value StreamableInGlobal)",
1923             PrintToString(Type(StreamableInGlobal{})));
1924   EXPECT_EQ(
1925       "('testing::gtest_printers_test::NonPrintable(index = 2)' with value "
1926       "1-byte object <11>)",
1927       PrintToString(Type(NonPrintable{})));
1928 }
1929 #endif  // GTEST_INTERNAL_HAS_VARIANT
1930 namespace {
1931 class string_ref;
1932 
1933 /**
1934  * This is a synthetic pointer to a fixed size string.
1935  */
1936 class string_ptr {
1937  public:
string_ptr(const char * data,size_t size)1938   string_ptr(const char* data, size_t size) : data_(data), size_(size) {}
1939 
operator ++()1940   string_ptr& operator++() noexcept {
1941     data_ += size_;
1942     return *this;
1943   }
1944 
1945   string_ref operator*() const noexcept;
1946 
1947  private:
1948   const char* data_;
1949   size_t size_;
1950 };
1951 
1952 /**
1953  * This is a synthetic reference of a fixed size string.
1954  */
1955 class string_ref {
1956  public:
string_ref(const char * data,size_t size)1957   string_ref(const char* data, size_t size) : data_(data), size_(size) {}
1958 
operator &() const1959   string_ptr operator&() const noexcept { return {data_, size_}; }  // NOLINT
1960 
operator ==(const char * s) const1961   bool operator==(const char* s) const noexcept {
1962     if (size_ > 0 && data_[size_ - 1] != 0) {
1963       return std::string(data_, size_) == std::string(s);
1964     } else {
1965       return std::string(data_) == std::string(s);
1966     }
1967   }
1968 
1969  private:
1970   const char* data_;
1971   size_t size_;
1972 };
1973 
operator *() const1974 string_ref string_ptr::operator*() const noexcept { return {data_, size_}; }
1975 
TEST(string_ref,compare)1976 TEST(string_ref, compare) {
1977   const char* s = "alex\0davidjohn\0";
1978   string_ptr ptr(s, 5);
1979   EXPECT_EQ(*ptr, "alex");
1980   EXPECT_TRUE(*ptr == "alex");
1981   ++ptr;
1982   EXPECT_EQ(*ptr, "david");
1983   EXPECT_TRUE(*ptr == "david");
1984   ++ptr;
1985   EXPECT_EQ(*ptr, "john");
1986 }
1987 
1988 }  // namespace
1989 
1990 }  // namespace gtest_printers_test
1991 }  // namespace testing
1992