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