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