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