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