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