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