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 // Floating-points.
TEST(PrintBuiltInTypeTest,FloatingPoints)453 TEST(PrintBuiltInTypeTest, FloatingPoints) {
454 EXPECT_EQ("1.5", Print(1.5f)); // float
455 EXPECT_EQ("-2.5", Print(-2.5)); // double
456 }
457
458 // Since ::std::stringstream::operator<<(const void *) formats the pointer
459 // output differently with different compilers, we have to create the expected
460 // output first and use it as our expectation.
PrintPointer(const void * p)461 static std::string PrintPointer(const void* p) {
462 ::std::stringstream expected_result_stream;
463 expected_result_stream << p;
464 return expected_result_stream.str();
465 }
466
467 // Tests printing C strings.
468
469 // const char*.
TEST(PrintCStringTest,Const)470 TEST(PrintCStringTest, Const) {
471 const char* p = "World";
472 EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p));
473 }
474
475 // char*.
TEST(PrintCStringTest,NonConst)476 TEST(PrintCStringTest, NonConst) {
477 char p[] = "Hi";
478 EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"",
479 Print(static_cast<char*>(p)));
480 }
481
482 // NULL C string.
TEST(PrintCStringTest,Null)483 TEST(PrintCStringTest, Null) {
484 const char* p = nullptr;
485 EXPECT_EQ("NULL", Print(p));
486 }
487
488 // Tests that C strings are escaped properly.
TEST(PrintCStringTest,EscapesProperly)489 TEST(PrintCStringTest, EscapesProperly) {
490 const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
491 EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f"
492 "\\n\\r\\t\\v\\x7F\\xFF a\"",
493 Print(p));
494 }
495
496 #ifdef __cpp_char8_t
497 // const char8_t*.
TEST(PrintU8StringTest,Const)498 TEST(PrintU8StringTest, Const) {
499 const char8_t* p = u8"界";
500 EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE7\\x95\\x8C\"", Print(p));
501 }
502
503 // char8_t*.
TEST(PrintU8StringTest,NonConst)504 TEST(PrintU8StringTest, NonConst) {
505 char8_t p[] = u8"世";
506 EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE4\\xB8\\x96\"",
507 Print(static_cast<char8_t*>(p)));
508 }
509
510 // NULL u8 string.
TEST(PrintU8StringTest,Null)511 TEST(PrintU8StringTest, Null) {
512 const char8_t* p = nullptr;
513 EXPECT_EQ("NULL", Print(p));
514 }
515
516 // Tests that u8 strings are escaped properly.
TEST(PrintU8StringTest,EscapesProperly)517 TEST(PrintU8StringTest, EscapesProperly) {
518 const char8_t* p = u8"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 世界";
519 EXPECT_EQ(PrintPointer(p) +
520 " pointing to u8\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
521 "hello \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
522 Print(p));
523 }
524 #endif
525
526 // const char16_t*.
TEST(PrintU16StringTest,Const)527 TEST(PrintU16StringTest, Const) {
528 const char16_t* p = u"界";
529 EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x754C\"", Print(p));
530 }
531
532 // char16_t*.
TEST(PrintU16StringTest,NonConst)533 TEST(PrintU16StringTest, NonConst) {
534 char16_t p[] = u"世";
535 EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x4E16\"",
536 Print(static_cast<char16_t*>(p)));
537 }
538
539 // NULL u16 string.
TEST(PrintU16StringTest,Null)540 TEST(PrintU16StringTest, Null) {
541 const char16_t* p = nullptr;
542 EXPECT_EQ("NULL", Print(p));
543 }
544
545 // Tests that u16 strings are escaped properly.
TEST(PrintU16StringTest,EscapesProperly)546 TEST(PrintU16StringTest, EscapesProperly) {
547 const char16_t* p = u"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 世界";
548 EXPECT_EQ(PrintPointer(p) +
549 " pointing to u\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
550 "hello \\x4E16\\x754C\"",
551 Print(p));
552 }
553
554 // const char32_t*.
TEST(PrintU32StringTest,Const)555 TEST(PrintU32StringTest, Const) {
556 const char32_t* p = U"️";
557 EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F5FA\\xFE0F\"", Print(p));
558 }
559
560 // char32_t*.
TEST(PrintU32StringTest,NonConst)561 TEST(PrintU32StringTest, NonConst) {
562 char32_t p[] = U"";
563 EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F30C\"",
564 Print(static_cast<char32_t*>(p)));
565 }
566
567 // NULL u32 string.
TEST(PrintU32StringTest,Null)568 TEST(PrintU32StringTest, Null) {
569 const char32_t* p = nullptr;
570 EXPECT_EQ("NULL", Print(p));
571 }
572
573 // Tests that u32 strings are escaped properly.
TEST(PrintU32StringTest,EscapesProperly)574 TEST(PrintU32StringTest, EscapesProperly) {
575 const char32_t* p = U"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello ️";
576 EXPECT_EQ(PrintPointer(p) +
577 " pointing to U\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
578 "hello \\x1F5FA\\xFE0F\"",
579 Print(p));
580 }
581
582 // MSVC compiler can be configured to define whar_t as a typedef
583 // of unsigned short. Defining an overload for const wchar_t* in that case
584 // would cause pointers to unsigned shorts be printed as wide strings,
585 // possibly accessing more memory than intended and causing invalid
586 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
587 // wchar_t is implemented as a native type.
588 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
589
590 // const wchar_t*.
TEST(PrintWideCStringTest,Const)591 TEST(PrintWideCStringTest, Const) {
592 const wchar_t* p = L"World";
593 EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p));
594 }
595
596 // wchar_t*.
TEST(PrintWideCStringTest,NonConst)597 TEST(PrintWideCStringTest, NonConst) {
598 wchar_t p[] = L"Hi";
599 EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"",
600 Print(static_cast<wchar_t*>(p)));
601 }
602
603 // NULL wide C string.
TEST(PrintWideCStringTest,Null)604 TEST(PrintWideCStringTest, Null) {
605 const wchar_t* p = nullptr;
606 EXPECT_EQ("NULL", Print(p));
607 }
608
609 // Tests that wide C strings are escaped properly.
TEST(PrintWideCStringTest,EscapesProperly)610 TEST(PrintWideCStringTest, EscapesProperly) {
611 const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r',
612 '\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'};
613 EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f"
614 "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
615 Print(static_cast<const wchar_t*>(s)));
616 }
617 #endif // native wchar_t
618
619 // Tests printing pointers to other char types.
620
621 // signed char*.
TEST(PrintCharPointerTest,SignedChar)622 TEST(PrintCharPointerTest, SignedChar) {
623 signed char* p = reinterpret_cast<signed char*>(0x1234);
624 EXPECT_EQ(PrintPointer(p), Print(p));
625 p = nullptr;
626 EXPECT_EQ("NULL", Print(p));
627 }
628
629 // const signed char*.
TEST(PrintCharPointerTest,ConstSignedChar)630 TEST(PrintCharPointerTest, ConstSignedChar) {
631 signed char* p = reinterpret_cast<signed char*>(0x1234);
632 EXPECT_EQ(PrintPointer(p), Print(p));
633 p = nullptr;
634 EXPECT_EQ("NULL", Print(p));
635 }
636
637 // unsigned char*.
TEST(PrintCharPointerTest,UnsignedChar)638 TEST(PrintCharPointerTest, UnsignedChar) {
639 unsigned char* p = reinterpret_cast<unsigned char*>(0x1234);
640 EXPECT_EQ(PrintPointer(p), Print(p));
641 p = nullptr;
642 EXPECT_EQ("NULL", Print(p));
643 }
644
645 // const unsigned char*.
TEST(PrintCharPointerTest,ConstUnsignedChar)646 TEST(PrintCharPointerTest, ConstUnsignedChar) {
647 const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234);
648 EXPECT_EQ(PrintPointer(p), Print(p));
649 p = nullptr;
650 EXPECT_EQ("NULL", Print(p));
651 }
652
653 // Tests printing pointers to simple, built-in types.
654
655 // bool*.
TEST(PrintPointerToBuiltInTypeTest,Bool)656 TEST(PrintPointerToBuiltInTypeTest, Bool) {
657 bool* p = reinterpret_cast<bool*>(0xABCD);
658 EXPECT_EQ(PrintPointer(p), Print(p));
659 p = nullptr;
660 EXPECT_EQ("NULL", Print(p));
661 }
662
663 // void*.
TEST(PrintPointerToBuiltInTypeTest,Void)664 TEST(PrintPointerToBuiltInTypeTest, Void) {
665 void* p = reinterpret_cast<void*>(0xABCD);
666 EXPECT_EQ(PrintPointer(p), Print(p));
667 p = nullptr;
668 EXPECT_EQ("NULL", Print(p));
669 }
670
671 // const void*.
TEST(PrintPointerToBuiltInTypeTest,ConstVoid)672 TEST(PrintPointerToBuiltInTypeTest, ConstVoid) {
673 const void* p = reinterpret_cast<const void*>(0xABCD);
674 EXPECT_EQ(PrintPointer(p), Print(p));
675 p = nullptr;
676 EXPECT_EQ("NULL", Print(p));
677 }
678
679 // Tests printing pointers to pointers.
TEST(PrintPointerToPointerTest,IntPointerPointer)680 TEST(PrintPointerToPointerTest, IntPointerPointer) {
681 int** p = reinterpret_cast<int**>(0xABCD);
682 EXPECT_EQ(PrintPointer(p), Print(p));
683 p = nullptr;
684 EXPECT_EQ("NULL", Print(p));
685 }
686
687 // Tests printing (non-member) function pointers.
688
MyFunction(int)689 void MyFunction(int /* n */) {}
690
TEST(PrintPointerTest,NonMemberFunctionPointer)691 TEST(PrintPointerTest, NonMemberFunctionPointer) {
692 // We cannot directly cast &MyFunction to const void* because the
693 // standard disallows casting between pointers to functions and
694 // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
695 // this limitation.
696 EXPECT_EQ(
697 PrintPointer(reinterpret_cast<const void*>(
698 reinterpret_cast<internal::BiggestInt>(&MyFunction))),
699 Print(&MyFunction));
700 int (*p)(bool) = NULL; // NOLINT
701 EXPECT_EQ("NULL", Print(p));
702 }
703
704 // An assertion predicate determining whether a one string is a prefix for
705 // another.
706 template <typename StringType>
HasPrefix(const StringType & str,const StringType & prefix)707 AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
708 if (str.find(prefix, 0) == 0)
709 return AssertionSuccess();
710
711 const bool is_wide_string = sizeof(prefix[0]) > 1;
712 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
713 return AssertionFailure()
714 << begin_string_quote << prefix << "\" is not a prefix of "
715 << begin_string_quote << str << "\"\n";
716 }
717
718 // Tests printing member variable pointers. Although they are called
719 // pointers, they don't point to a location in the address space.
720 // Their representation is implementation-defined. Thus they will be
721 // printed as raw bytes.
722
723 struct Foo {
724 public:
~Footesting::gtest_printers_test::Foo725 virtual ~Foo() {}
MyMethodtesting::gtest_printers_test::Foo726 int MyMethod(char x) { return x + 1; }
MyVirtualMethodtesting::gtest_printers_test::Foo727 virtual char MyVirtualMethod(int /* n */) { return 'a'; }
728
729 int value;
730 };
731
TEST(PrintPointerTest,MemberVariablePointer)732 TEST(PrintPointerTest, MemberVariablePointer) {
733 EXPECT_TRUE(HasPrefix(Print(&Foo::value),
734 Print(sizeof(&Foo::value)) + "-byte object "));
735 int Foo::*p = NULL; // NOLINT
736 EXPECT_TRUE(HasPrefix(Print(p),
737 Print(sizeof(p)) + "-byte object "));
738 }
739
740 // Tests printing member function pointers. Although they are called
741 // pointers, they don't point to a location in the address space.
742 // Their representation is implementation-defined. Thus they will be
743 // printed as raw bytes.
TEST(PrintPointerTest,MemberFunctionPointer)744 TEST(PrintPointerTest, MemberFunctionPointer) {
745 EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod),
746 Print(sizeof(&Foo::MyMethod)) + "-byte object "));
747 EXPECT_TRUE(
748 HasPrefix(Print(&Foo::MyVirtualMethod),
749 Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
750 int (Foo::*p)(char) = NULL; // NOLINT
751 EXPECT_TRUE(HasPrefix(Print(p),
752 Print(sizeof(p)) + "-byte object "));
753 }
754
755 // Tests printing C arrays.
756
757 // The difference between this and Print() is that it ensures that the
758 // argument is a reference to an array.
759 template <typename T, size_t N>
PrintArrayHelper(T (& a)[N])760 std::string PrintArrayHelper(T (&a)[N]) {
761 return Print(a);
762 }
763
764 // One-dimensional array.
TEST(PrintArrayTest,OneDimensionalArray)765 TEST(PrintArrayTest, OneDimensionalArray) {
766 int a[5] = { 1, 2, 3, 4, 5 };
767 EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
768 }
769
770 // Two-dimensional array.
TEST(PrintArrayTest,TwoDimensionalArray)771 TEST(PrintArrayTest, TwoDimensionalArray) {
772 int a[2][5] = {
773 { 1, 2, 3, 4, 5 },
774 { 6, 7, 8, 9, 0 }
775 };
776 EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
777 }
778
779 // Array of const elements.
TEST(PrintArrayTest,ConstArray)780 TEST(PrintArrayTest, ConstArray) {
781 const bool a[1] = { false };
782 EXPECT_EQ("{ false }", PrintArrayHelper(a));
783 }
784
785 // char array without terminating NUL.
TEST(PrintArrayTest,CharArrayWithNoTerminatingNul)786 TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {
787 // Array a contains '\0' in the middle and doesn't end with '\0'.
788 char a[] = { 'H', '\0', 'i' };
789 EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
790 }
791
792 // char array with terminating NUL.
TEST(PrintArrayTest,CharArrayWithTerminatingNul)793 TEST(PrintArrayTest, CharArrayWithTerminatingNul) {
794 const char a[] = "\0Hi";
795 EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a));
796 }
797
798 #ifdef __cpp_char8_t
799 // char_t array without terminating NUL.
TEST(PrintArrayTest,Char8ArrayWithNoTerminatingNul)800 TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) {
801 // Array a contains '\0' in the middle and doesn't end with '\0'.
802 const char8_t a[] = {u8'H', u8'\0', u8'i'};
803 EXPECT_EQ("u8\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
804 }
805
806 // char8_t array with terminating NUL.
807 TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) {
808 const char8_t a[] = u8"\0世界";
809 EXPECT_EQ(
810 "u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
811 PrintArrayHelper(a));
812 }
813 #endif
814
815 // const char16_t array without terminating NUL.
816 TEST(PrintArrayTest, Char16ArrayWithNoTerminatingNul) {
817 // Array a contains '\0' in the middle and doesn't end with '\0'.
818 const char16_t a[] = {u'こ', u'\0', u'ん', u'に', u'ち', u'は'};
819 EXPECT_EQ("u\"\\x3053\\0\\x3093\\x306B\\x3061\\x306F\" (no terminating NUL)",
820 PrintArrayHelper(a));
821 }
822
823 // char16_t array with terminating NUL.
824 TEST(PrintArrayTest, Char16ArrayWithTerminatingNul) {
825 const char16_t a[] = u"\0こんにちは";
826 EXPECT_EQ("u\"\\0\\x3053\\x3093\\x306B\\x3061\\x306F\"", PrintArrayHelper(a));
827 }
828
829 // char32_t array without terminating NUL.
830 TEST(PrintArrayTest, Char32ArrayWithNoTerminatingNul) {
831 // Array a contains '\0' in the middle and doesn't end with '\0'.
832 const char32_t a[] = {U'', U'\0', U''};
833 EXPECT_EQ("U\"\\x1F44B\\0\\x1F30C\" (no terminating NUL)",
834 PrintArrayHelper(a));
835 }
836
837 // char32_t array with terminating NUL.
838 TEST(PrintArrayTest, Char32ArrayWithTerminatingNul) {
839 const char32_t a[] = U"\0";
840 EXPECT_EQ("U\"\\0\\x1F44B\\x1F30C\"", PrintArrayHelper(a));
841 }
842
843 // wchar_t array without terminating NUL.
844 TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) {
845 // Array a contains '\0' in the middle and doesn't end with '\0'.
846 const wchar_t a[] = {L'H', L'\0', L'i'};
847 EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
848 }
849
850 // wchar_t array with terminating NUL.
851 TEST(PrintArrayTest, WCharArrayWithTerminatingNul) {
852 const wchar_t a[] = L"\0Hi";
853 EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a));
854 }
855
856 // Array of objects.
857 TEST(PrintArrayTest, ObjectArray) {
858 std::string a[3] = {"Hi", "Hello", "Ni hao"};
859 EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a));
860 }
861
862 // Array with many elements.
863 TEST(PrintArrayTest, BigArray) {
864 int a[100] = { 1, 2, 3 };
865 EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }",
866 PrintArrayHelper(a));
867 }
868
869 // Tests printing ::string and ::std::string.
870
871 // ::std::string.
872 TEST(PrintStringTest, StringInStdNamespace) {
873 const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
874 const ::std::string str(s, sizeof(s));
875 EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
876 Print(str));
877 }
878
879 TEST(PrintStringTest, StringAmbiguousHex) {
880 // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of:
881 // '\x6', '\x6B', or '\x6BA'.
882
883 // a hex escaping sequence following by a decimal digit
884 EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3")));
885 // a hex escaping sequence following by a hex digit (lower-case)
886 EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas")));
887 // a hex escaping sequence following by a hex digit (upper-case)
888 EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA")));
889 // a hex escaping sequence following by a non-xdigit
890 EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
891 }
892
893 // Tests printing ::std::wstring.
894 #if GTEST_HAS_STD_WSTRING
895 // ::std::wstring.
896 TEST(PrintWideStringTest, StringInStdNamespace) {
897 const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
898 const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t));
899 EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
900 "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
901 Print(str));
902 }
903
904 TEST(PrintWideStringTest, StringAmbiguousHex) {
905 // same for wide strings.
906 EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3")));
907 EXPECT_EQ("L\"mm\\x6\" L\"bananas\"",
908 Print(::std::wstring(L"mm\x6" L"bananas")));
909 EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"",
910 Print(::std::wstring(L"NOM\x6" L"BANANA")));
911 EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
912 }
913 #endif // GTEST_HAS_STD_WSTRING
914
915 #ifdef __cpp_char8_t
916 TEST(PrintStringTest, U8String) {
917 std::u8string str = u8"Hello, 世界";
918 EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
919 EXPECT_EQ("u8\"Hello, \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", Print(str));
920 }
921 #endif
922
923 TEST(PrintStringTest, U16String) {
924 std::u16string str = u"Hello, 世界";
925 EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
926 EXPECT_EQ("u\"Hello, \\x4E16\\x754C\"", Print(str));
927 }
928
929 TEST(PrintStringTest, U32String) {
930 std::u32string str = U"Hello, ️";
931 EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type
932 EXPECT_EQ("U\"Hello, \\x1F5FA\\xFE0F\"", Print(str));
933 }
934
935 // Tests printing types that support generic streaming (i.e. streaming
936 // to std::basic_ostream<Char, CharTraits> for any valid Char and
937 // CharTraits types).
938
939 // Tests printing a non-template type that supports generic streaming.
940
941 class AllowsGenericStreaming {};
942
943 template <typename Char, typename CharTraits>
944 std::basic_ostream<Char, CharTraits>& operator<<(
945 std::basic_ostream<Char, CharTraits>& os,
946 const AllowsGenericStreaming& /* a */) {
947 return os << "AllowsGenericStreaming";
948 }
949
950 TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) {
951 AllowsGenericStreaming a;
952 EXPECT_EQ("AllowsGenericStreaming", Print(a));
953 }
954
955 // Tests printing a template type that supports generic streaming.
956
957 template <typename T>
958 class AllowsGenericStreamingTemplate {};
959
960 template <typename Char, typename CharTraits, typename T>
961 std::basic_ostream<Char, CharTraits>& operator<<(
962 std::basic_ostream<Char, CharTraits>& os,
963 const AllowsGenericStreamingTemplate<T>& /* a */) {
964 return os << "AllowsGenericStreamingTemplate";
965 }
966
967 TEST(PrintTypeWithGenericStreamingTest, TemplateType) {
968 AllowsGenericStreamingTemplate<int> a;
969 EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a));
970 }
971
972 // Tests printing a type that supports generic streaming and can be
973 // implicitly converted to another printable type.
974
975 template <typename T>
976 class AllowsGenericStreamingAndImplicitConversionTemplate {
977 public:
operator bool() const978 operator bool() const { return false; }
979 };
980
981 template <typename Char, typename CharTraits, typename T>
982 std::basic_ostream<Char, CharTraits>& operator<<(
983 std::basic_ostream<Char, CharTraits>& os,
984 const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) {
985 return os << "AllowsGenericStreamingAndImplicitConversionTemplate";
986 }
987
988 TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
989 AllowsGenericStreamingAndImplicitConversionTemplate<int> a;
990 EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
991 }
992
993 #if GTEST_INTERNAL_HAS_STRING_VIEW
994
995 // Tests printing internal::StringView.
996
997 TEST(PrintStringViewTest, SimpleStringView) {
998 const internal::StringView sp = "Hello";
999 EXPECT_EQ("\"Hello\"", Print(sp));
1000 }
1001
1002 TEST(PrintStringViewTest, UnprintableCharacters) {
1003 const char str[] = "NUL (\0) and \r\t";
1004 const internal::StringView sp(str, sizeof(str) - 1);
1005 EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
1006 }
1007
1008 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
1009
1010 // Tests printing STL containers.
1011
1012 TEST(PrintStlContainerTest, EmptyDeque) {
1013 deque<char> empty;
1014 EXPECT_EQ("{}", Print(empty));
1015 }
1016
1017 TEST(PrintStlContainerTest, NonEmptyDeque) {
1018 deque<int> non_empty;
1019 non_empty.push_back(1);
1020 non_empty.push_back(3);
1021 EXPECT_EQ("{ 1, 3 }", Print(non_empty));
1022 }
1023
1024
1025 TEST(PrintStlContainerTest, OneElementHashMap) {
1026 ::std::unordered_map<int, char> map1;
1027 map1[1] = 'a';
1028 EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1));
1029 }
1030
1031 TEST(PrintStlContainerTest, HashMultiMap) {
1032 ::std::unordered_multimap<int, bool> map1;
1033 map1.insert(make_pair(5, true));
1034 map1.insert(make_pair(5, false));
1035
1036 // Elements of hash_multimap can be printed in any order.
1037 const std::string result = Print(map1);
1038 EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
1039 result == "{ (5, false), (5, true) }")
1040 << " where Print(map1) returns \"" << result << "\".";
1041 }
1042
1043
1044
1045 TEST(PrintStlContainerTest, HashSet) {
1046 ::std::unordered_set<int> set1;
1047 set1.insert(1);
1048 EXPECT_EQ("{ 1 }", Print(set1));
1049 }
1050
1051 TEST(PrintStlContainerTest, HashMultiSet) {
1052 const int kSize = 5;
1053 int a[kSize] = { 1, 1, 2, 5, 1 };
1054 ::std::unordered_multiset<int> set1(a, a + kSize);
1055
1056 // Elements of hash_multiset can be printed in any order.
1057 const std::string result = Print(set1);
1058 const std::string expected_pattern = "{ d, d, d, d, d }"; // d means a digit.
1059
1060 // Verifies the result matches the expected pattern; also extracts
1061 // the numbers in the result.
1062 ASSERT_EQ(expected_pattern.length(), result.length());
1063 std::vector<int> numbers;
1064 for (size_t i = 0; i != result.length(); i++) {
1065 if (expected_pattern[i] == 'd') {
1066 ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
1067 numbers.push_back(result[i] - '0');
1068 } else {
1069 EXPECT_EQ(expected_pattern[i], result[i]) << " where result is "
1070 << result;
1071 }
1072 }
1073
1074 // Makes sure the result contains the right numbers.
1075 std::sort(numbers.begin(), numbers.end());
1076 std::sort(a, a + kSize);
1077 EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
1078 }
1079
1080
1081 TEST(PrintStlContainerTest, List) {
1082 const std::string a[] = {"hello", "world"};
1083 const list<std::string> strings(a, a + 2);
1084 EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings));
1085 }
1086
1087 TEST(PrintStlContainerTest, Map) {
1088 map<int, bool> map1;
1089 map1[1] = true;
1090 map1[5] = false;
1091 map1[3] = true;
1092 EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1));
1093 }
1094
1095 TEST(PrintStlContainerTest, MultiMap) {
1096 multimap<bool, int> map1;
1097 // The make_pair template function would deduce the type as
1098 // pair<bool, int> here, and since the key part in a multimap has to
1099 // be constant, without a templated ctor in the pair class (as in
1100 // libCstd on Solaris), make_pair call would fail to compile as no
1101 // implicit conversion is found. Thus explicit typename is used
1102 // here instead.
1103 map1.insert(pair<const bool, int>(true, 0));
1104 map1.insert(pair<const bool, int>(true, 1));
1105 map1.insert(pair<const bool, int>(false, 2));
1106 EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1));
1107 }
1108
1109 TEST(PrintStlContainerTest, Set) {
1110 const unsigned int a[] = { 3, 0, 5 };
1111 set<unsigned int> set1(a, a + 3);
1112 EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
1113 }
1114
1115 TEST(PrintStlContainerTest, MultiSet) {
1116 const int a[] = { 1, 1, 2, 5, 1 };
1117 multiset<int> set1(a, a + 5);
1118 EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
1119 }
1120
1121
1122 TEST(PrintStlContainerTest, SinglyLinkedList) {
1123 int a[] = { 9, 2, 8 };
1124 const std::forward_list<int> ints(a, a + 3);
1125 EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
1126 }
1127
1128 TEST(PrintStlContainerTest, Pair) {
1129 pair<const bool, int> p(true, 5);
1130 EXPECT_EQ("(true, 5)", Print(p));
1131 }
1132
1133 TEST(PrintStlContainerTest, Vector) {
1134 vector<int> v;
1135 v.push_back(1);
1136 v.push_back(2);
1137 EXPECT_EQ("{ 1, 2 }", Print(v));
1138 }
1139
1140 TEST(PrintStlContainerTest, LongSequence) {
1141 const int a[100] = { 1, 2, 3 };
1142 const vector<int> v(a, a + 100);
1143 EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
1144 "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v));
1145 }
1146
1147 TEST(PrintStlContainerTest, NestedContainer) {
1148 const int a1[] = { 1, 2 };
1149 const int a2[] = { 3, 4, 5 };
1150 const list<int> l1(a1, a1 + 2);
1151 const list<int> l2(a2, a2 + 3);
1152
1153 vector<list<int> > v;
1154 v.push_back(l1);
1155 v.push_back(l2);
1156 EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
1157 }
1158
1159 TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
1160 const int a[3] = { 1, 2, 3 };
1161 NativeArray<int> b(a, 3, RelationToSourceReference());
1162 EXPECT_EQ("{ 1, 2, 3 }", Print(b));
1163 }
1164
1165 TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
1166 const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
1167 NativeArray<int[3]> b(a, 2, RelationToSourceReference());
1168 EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
1169 }
1170
1171 // Tests that a class named iterator isn't treated as a container.
1172
1173 struct iterator {
1174 char x;
1175 };
1176
1177 TEST(PrintStlContainerTest, Iterator) {
1178 iterator it = {};
1179 EXPECT_EQ("1-byte object <00>", Print(it));
1180 }
1181
1182 // Tests that a class named const_iterator isn't treated as a container.
1183
1184 struct const_iterator {
1185 char x;
1186 };
1187
1188 TEST(PrintStlContainerTest, ConstIterator) {
1189 const_iterator it = {};
1190 EXPECT_EQ("1-byte object <00>", Print(it));
1191 }
1192
1193 // Tests printing ::std::tuples.
1194
1195 // Tuples of various arities.
1196 TEST(PrintStdTupleTest, VariousSizes) {
1197 ::std::tuple<> t0;
1198 EXPECT_EQ("()", Print(t0));
1199
1200 ::std::tuple<int> t1(5);
1201 EXPECT_EQ("(5)", Print(t1));
1202
1203 ::std::tuple<char, bool> t2('a', true);
1204 EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
1205
1206 ::std::tuple<bool, int, int> t3(false, 2, 3);
1207 EXPECT_EQ("(false, 2, 3)", Print(t3));
1208
1209 ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4);
1210 EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
1211
1212 const char* const str = "8";
1213 ::std::tuple<bool, char, short, int32_t, int64_t, float, double, // NOLINT
1214 const char*, void*, std::string>
1215 t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT
1216 nullptr, "10");
1217 EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
1218 " pointing to \"8\", NULL, \"10\")",
1219 Print(t10));
1220 }
1221
1222 // Nested tuples.
1223 TEST(PrintStdTupleTest, NestedTuple) {
1224 ::std::tuple< ::std::tuple<int, bool>, char> nested(
1225 ::std::make_tuple(5, true), 'a');
1226 EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
1227 }
1228
1229 TEST(PrintNullptrT, Basic) {
1230 EXPECT_EQ("(nullptr)", Print(nullptr));
1231 }
1232
1233 TEST(PrintReferenceWrapper, Printable) {
1234 int x = 5;
1235 EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::ref(x)));
1236 EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::cref(x)));
1237 }
1238
1239 TEST(PrintReferenceWrapper, Unprintable) {
1240 ::foo::UnprintableInFoo up;
1241 EXPECT_EQ(
1242 "@" + PrintPointer(&up) +
1243 " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1244 Print(std::ref(up)));
1245 EXPECT_EQ(
1246 "@" + PrintPointer(&up) +
1247 " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1248 Print(std::cref(up)));
1249 }
1250
1251 // Tests printing user-defined unprintable types.
1252
1253 // Unprintable types in the global namespace.
1254 TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
1255 EXPECT_EQ("1-byte object <00>",
1256 Print(UnprintableTemplateInGlobal<char>()));
1257 }
1258
1259 // Unprintable types in a user namespace.
1260 TEST(PrintUnprintableTypeTest, InUserNamespace) {
1261 EXPECT_EQ("16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1262 Print(::foo::UnprintableInFoo()));
1263 }
1264
1265 // Unprintable types are that too big to be printed completely.
1266
1267 struct Big {
Bigtesting::gtest_printers_test::TEST::Big1268 Big() { memset(array, 0, sizeof(array)); }
1269 char array[257];
1270 };
1271
1272 TEST(PrintUnpritableTypeTest, BigObject) {
1273 EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
1274 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1275 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1276 "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
1277 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1278 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1279 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
1280 Print(Big()));
1281 }
1282
1283 // Tests printing user-defined streamable types.
1284
1285 // Streamable types in the global namespace.
1286 TEST(PrintStreamableTypeTest, InGlobalNamespace) {
1287 StreamableInGlobal x;
1288 EXPECT_EQ("StreamableInGlobal", Print(x));
1289 EXPECT_EQ("StreamableInGlobal*", Print(&x));
1290 }
1291
1292 // Printable template types in a user namespace.
1293 TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
1294 EXPECT_EQ("StreamableTemplateInFoo: 0",
1295 Print(::foo::StreamableTemplateInFoo<int>()));
1296 }
1297
1298 TEST(PrintStreamableTypeTest, TypeInUserNamespaceWithTemplatedStreamOperator) {
1299 EXPECT_EQ("TemplatedStreamableInFoo",
1300 Print(::foo::TemplatedStreamableInFoo()));
1301 }
1302
1303 TEST(PrintStreamableTypeTest, SubclassUsesSuperclassStreamOperator) {
1304 ParentClass parent;
1305 ChildClassWithStreamOperator child_stream;
1306 ChildClassWithoutStreamOperator child_no_stream;
1307 EXPECT_EQ("ParentClass", Print(parent));
1308 EXPECT_EQ("ChildClassWithStreamOperator", Print(child_stream));
1309 EXPECT_EQ("ParentClass", Print(child_no_stream));
1310 }
1311
1312 // Tests printing a user-defined recursive container type that has a <<
1313 // operator.
1314 TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
1315 ::foo::PathLike x;
1316 EXPECT_EQ("Streamable-PathLike", Print(x));
1317 const ::foo::PathLike cx;
1318 EXPECT_EQ("Streamable-PathLike", Print(cx));
1319 }
1320
1321 // Tests printing user-defined types that have a PrintTo() function.
1322 TEST(PrintPrintableTypeTest, InUserNamespace) {
1323 EXPECT_EQ("PrintableViaPrintTo: 0",
1324 Print(::foo::PrintableViaPrintTo()));
1325 }
1326
1327 // Tests printing a pointer to a user-defined type that has a <<
1328 // operator for its pointer.
1329 TEST(PrintPrintableTypeTest, PointerInUserNamespace) {
1330 ::foo::PointerPrintable x;
1331 EXPECT_EQ("PointerPrintable*", Print(&x));
1332 }
1333
1334 // Tests printing user-defined class template that have a PrintTo() function.
1335 TEST(PrintPrintableTypeTest, TemplateInUserNamespace) {
1336 EXPECT_EQ("PrintableViaPrintToTemplate: 5",
1337 Print(::foo::PrintableViaPrintToTemplate<int>(5)));
1338 }
1339
1340 // Tests that the universal printer prints both the address and the
1341 // value of a reference.
1342 TEST(PrintReferenceTest, PrintsAddressAndValue) {
1343 int n = 5;
1344 EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
1345
1346 int a[2][3] = {
1347 { 0, 1, 2 },
1348 { 3, 4, 5 }
1349 };
1350 EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
1351 PrintByRef(a));
1352
1353 const ::foo::UnprintableInFoo x;
1354 EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object "
1355 "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1356 PrintByRef(x));
1357 }
1358
1359 // Tests that the universal printer prints a function pointer passed by
1360 // reference.
1361 TEST(PrintReferenceTest, HandlesFunctionPointer) {
1362 void (*fp)(int n) = &MyFunction;
1363 const std::string fp_pointer_string =
1364 PrintPointer(reinterpret_cast<const void*>(&fp));
1365 // We cannot directly cast &MyFunction to const void* because the
1366 // standard disallows casting between pointers to functions and
1367 // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
1368 // this limitation.
1369 const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(
1370 reinterpret_cast<internal::BiggestInt>(fp)));
1371 EXPECT_EQ("@" + fp_pointer_string + " " + fp_string,
1372 PrintByRef(fp));
1373 }
1374
1375 // Tests that the universal printer prints a member function pointer
1376 // passed by reference.
1377 TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
1378 int (Foo::*p)(char ch) = &Foo::MyMethod;
1379 EXPECT_TRUE(HasPrefix(
1380 PrintByRef(p),
1381 "@" + PrintPointer(reinterpret_cast<const void*>(&p)) + " " +
1382 Print(sizeof(p)) + "-byte object "));
1383
1384 char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
1385 EXPECT_TRUE(HasPrefix(
1386 PrintByRef(p2),
1387 "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) + " " +
1388 Print(sizeof(p2)) + "-byte object "));
1389 }
1390
1391 // Tests that the universal printer prints a member variable pointer
1392 // passed by reference.
1393 TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
1394 int Foo::*p = &Foo::value; // NOLINT
1395 EXPECT_TRUE(HasPrefix(
1396 PrintByRef(p),
1397 "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object "));
1398 }
1399
1400 // Tests that FormatForComparisonFailureMessage(), which is used to print
1401 // an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion
1402 // fails, formats the operand in the desired way.
1403
1404 // scalar
1405 TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
1406 EXPECT_STREQ("123",
1407 FormatForComparisonFailureMessage(123, 124).c_str());
1408 }
1409
1410 // non-char pointer
1411 TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {
1412 int n = 0;
1413 EXPECT_EQ(PrintPointer(&n),
1414 FormatForComparisonFailureMessage(&n, &n).c_str());
1415 }
1416
1417 // non-char array
1418 TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
1419 // In expression 'array == x', 'array' is compared by pointer.
1420 // Therefore we want to print an array operand as a pointer.
1421 int n[] = { 1, 2, 3 };
1422 EXPECT_EQ(PrintPointer(n),
1423 FormatForComparisonFailureMessage(n, n).c_str());
1424 }
1425
1426 // Tests formatting a char pointer when it's compared with another pointer.
1427 // In this case we want to print it as a raw pointer, as the comparison is by
1428 // pointer.
1429
1430 // char pointer vs pointer
1431 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
1432 // In expression 'p == x', where 'p' and 'x' are (const or not) char
1433 // pointers, the operands are compared by pointer. Therefore we
1434 // want to print 'p' as a pointer instead of a C string (we don't
1435 // even know if it's supposed to point to a valid C string).
1436
1437 // const char*
1438 const char* s = "hello";
1439 EXPECT_EQ(PrintPointer(s),
1440 FormatForComparisonFailureMessage(s, s).c_str());
1441
1442 // char*
1443 char ch = 'a';
1444 EXPECT_EQ(PrintPointer(&ch),
1445 FormatForComparisonFailureMessage(&ch, &ch).c_str());
1446 }
1447
1448 // wchar_t pointer vs pointer
1449 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
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 wide C string (we don't
1453 // even know if it's supposed to point to a valid wide C string).
1454
1455 // const wchar_t*
1456 const wchar_t* s = L"hello";
1457 EXPECT_EQ(PrintPointer(s),
1458 FormatForComparisonFailureMessage(s, s).c_str());
1459
1460 // wchar_t*
1461 wchar_t ch = L'a';
1462 EXPECT_EQ(PrintPointer(&ch),
1463 FormatForComparisonFailureMessage(&ch, &ch).c_str());
1464 }
1465
1466 // Tests formatting a char pointer when it's compared to a string object.
1467 // In this case we want to print the char pointer as a C string.
1468
1469 // char pointer vs std::string
1470 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) {
1471 const char* s = "hello \"world";
1472 EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped.
1473 FormatForComparisonFailureMessage(s, ::std::string()).c_str());
1474
1475 // char*
1476 char str[] = "hi\1";
1477 char* p = str;
1478 EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped.
1479 FormatForComparisonFailureMessage(p, ::std::string()).c_str());
1480 }
1481
1482 #if GTEST_HAS_STD_WSTRING
1483 // wchar_t pointer vs std::wstring
1484 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) {
1485 const wchar_t* s = L"hi \"world";
1486 EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped.
1487 FormatForComparisonFailureMessage(s, ::std::wstring()).c_str());
1488
1489 // wchar_t*
1490 wchar_t str[] = L"hi\1";
1491 wchar_t* p = str;
1492 EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped.
1493 FormatForComparisonFailureMessage(p, ::std::wstring()).c_str());
1494 }
1495 #endif
1496
1497 // Tests formatting a char array when it's compared with a pointer or array.
1498 // In this case we want to print the array as a row pointer, as the comparison
1499 // is by pointer.
1500
1501 // char array vs pointer
1502 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) {
1503 char str[] = "hi \"world\"";
1504 char* p = nullptr;
1505 EXPECT_EQ(PrintPointer(str),
1506 FormatForComparisonFailureMessage(str, p).c_str());
1507 }
1508
1509 // char array vs char array
1510 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) {
1511 const char str[] = "hi \"world\"";
1512 EXPECT_EQ(PrintPointer(str),
1513 FormatForComparisonFailureMessage(str, str).c_str());
1514 }
1515
1516 // wchar_t array vs pointer
1517 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) {
1518 wchar_t str[] = L"hi \"world\"";
1519 wchar_t* p = nullptr;
1520 EXPECT_EQ(PrintPointer(str),
1521 FormatForComparisonFailureMessage(str, p).c_str());
1522 }
1523
1524 // wchar_t array vs wchar_t array
1525 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) {
1526 const wchar_t str[] = L"hi \"world\"";
1527 EXPECT_EQ(PrintPointer(str),
1528 FormatForComparisonFailureMessage(str, str).c_str());
1529 }
1530
1531 // Tests formatting a char array when it's compared with a string object.
1532 // In this case we want to print the array as a C string.
1533
1534 // char array vs std::string
1535 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) {
1536 const char str[] = "hi \"world\"";
1537 EXPECT_STREQ("\"hi \\\"world\\\"\"", // The content should be escaped.
1538 FormatForComparisonFailureMessage(str, ::std::string()).c_str());
1539 }
1540
1541 #if GTEST_HAS_STD_WSTRING
1542 // wchar_t array vs std::wstring
1543 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
1544 const wchar_t str[] = L"hi \"w\0rld\"";
1545 EXPECT_STREQ(
1546 "L\"hi \\\"w\"", // The content should be escaped.
1547 // Embedded NUL terminates the string.
1548 FormatForComparisonFailureMessage(str, ::std::wstring()).c_str());
1549 }
1550 #endif
1551
1552 // Useful for testing PrintToString(). We cannot use EXPECT_EQ()
1553 // there as its implementation uses PrintToString(). The caller must
1554 // ensure that 'value' has no side effect.
1555 #define EXPECT_PRINT_TO_STRING_(value, expected_string) \
1556 EXPECT_TRUE(PrintToString(value) == (expected_string)) \
1557 << " where " #value " prints as " << (PrintToString(value))
1558
1559 TEST(PrintToStringTest, WorksForScalar) {
1560 EXPECT_PRINT_TO_STRING_(123, "123");
1561 }
1562
1563 TEST(PrintToStringTest, WorksForPointerToConstChar) {
1564 const char* p = "hello";
1565 EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1566 }
1567
1568 TEST(PrintToStringTest, WorksForPointerToNonConstChar) {
1569 char s[] = "hello";
1570 char* p = s;
1571 EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1572 }
1573
1574 TEST(PrintToStringTest, EscapesForPointerToConstChar) {
1575 const char* p = "hello\n";
1576 EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\"");
1577 }
1578
1579 TEST(PrintToStringTest, EscapesForPointerToNonConstChar) {
1580 char s[] = "hello\1";
1581 char* p = s;
1582 EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\"");
1583 }
1584
1585 TEST(PrintToStringTest, WorksForArray) {
1586 int n[3] = { 1, 2, 3 };
1587 EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }");
1588 }
1589
1590 TEST(PrintToStringTest, WorksForCharArray) {
1591 char s[] = "hello";
1592 EXPECT_PRINT_TO_STRING_(s, "\"hello\"");
1593 }
1594
1595 TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {
1596 const char str_with_nul[] = "hello\0 world";
1597 EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\"");
1598
1599 char mutable_str_with_nul[] = "hello\0 world";
1600 EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\"");
1601 }
1602
1603 TEST(PrintToStringTest, ContainsNonLatin) {
1604 // Sanity test with valid UTF-8. Prints both in hex and as text.
1605 std::string non_ascii_str = ::std::string("오전 4:30");
1606 EXPECT_PRINT_TO_STRING_(non_ascii_str,
1607 "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n"
1608 " As Text: \"오전 4:30\"");
1609 non_ascii_str = ::std::string("From ä — ẑ");
1610 EXPECT_PRINT_TO_STRING_(non_ascii_str,
1611 "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\""
1612 "\n As Text: \"From ä — ẑ\"");
1613 }
1614
1615 TEST(IsValidUTF8Test, IllFormedUTF8) {
1616 // The following test strings are ill-formed UTF-8 and are printed
1617 // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is
1618 // expected to fail, thus output does not contain "As Text:".
1619
1620 static const char *const kTestdata[][2] = {
1621 // 2-byte lead byte followed by a single-byte character.
1622 {"\xC3\x74", "\"\\xC3t\""},
1623 // Valid 2-byte character followed by an orphan trail byte.
1624 {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""},
1625 // Lead byte without trail byte.
1626 {"abc\xC3", "\"abc\\xC3\""},
1627 // 3-byte lead byte, single-byte character, orphan trail byte.
1628 {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""},
1629 // Truncated 3-byte character.
1630 {"\xE2\x80", "\"\\xE2\\x80\""},
1631 // Truncated 3-byte character followed by valid 2-byte char.
1632 {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""},
1633 // Truncated 3-byte character followed by a single-byte character.
1634 {"\xE2\x80\x7A", "\"\\xE2\\x80z\""},
1635 // 3-byte lead byte followed by valid 3-byte character.
1636 {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""},
1637 // 4-byte lead byte followed by valid 3-byte character.
1638 {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""},
1639 // Truncated 4-byte character.
1640 {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""},
1641 // Invalid UTF-8 byte sequences embedded in other chars.
1642 {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""},
1643 {"abc\xC3\x84\xE2\x80\xC3\x84xyz",
1644 "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""},
1645 // Non-shortest UTF-8 byte sequences are also ill-formed.
1646 // The classics: xC0, xC1 lead byte.
1647 {"\xC0\x80", "\"\\xC0\\x80\""},
1648 {"\xC1\x81", "\"\\xC1\\x81\""},
1649 // Non-shortest sequences.
1650 {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
1651 {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
1652 // Last valid code point before surrogate range, should be printed as text,
1653 // too.
1654 {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"\""},
1655 // Start of surrogate lead. Surrogates are not printed as text.
1656 {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""},
1657 // Last non-private surrogate lead.
1658 {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""},
1659 // First private-use surrogate lead.
1660 {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""},
1661 // Last private-use surrogate lead.
1662 {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
1663 // Mid-point of surrogate trail.
1664 {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
1665 // First valid code point after surrogate range, should be printed as text,
1666 // too.
1667 {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""}
1668 };
1669
1670 for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) {
1671 EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
1672 }
1673 }
1674
1675 #undef EXPECT_PRINT_TO_STRING_
1676
1677 TEST(UniversalTersePrintTest, WorksForNonReference) {
1678 ::std::stringstream ss;
1679 UniversalTersePrint(123, &ss);
1680 EXPECT_EQ("123", ss.str());
1681 }
1682
1683 TEST(UniversalTersePrintTest, WorksForReference) {
1684 const int& n = 123;
1685 ::std::stringstream ss;
1686 UniversalTersePrint(n, &ss);
1687 EXPECT_EQ("123", ss.str());
1688 }
1689
1690 TEST(UniversalTersePrintTest, WorksForCString) {
1691 const char* s1 = "abc";
1692 ::std::stringstream ss1;
1693 UniversalTersePrint(s1, &ss1);
1694 EXPECT_EQ("\"abc\"", ss1.str());
1695
1696 char* s2 = const_cast<char*>(s1);
1697 ::std::stringstream ss2;
1698 UniversalTersePrint(s2, &ss2);
1699 EXPECT_EQ("\"abc\"", ss2.str());
1700
1701 const char* s3 = nullptr;
1702 ::std::stringstream ss3;
1703 UniversalTersePrint(s3, &ss3);
1704 EXPECT_EQ("NULL", ss3.str());
1705 }
1706
1707 TEST(UniversalPrintTest, WorksForNonReference) {
1708 ::std::stringstream ss;
1709 UniversalPrint(123, &ss);
1710 EXPECT_EQ("123", ss.str());
1711 }
1712
1713 TEST(UniversalPrintTest, WorksForReference) {
1714 const int& n = 123;
1715 ::std::stringstream ss;
1716 UniversalPrint(n, &ss);
1717 EXPECT_EQ("123", ss.str());
1718 }
1719
1720 TEST(UniversalPrintTest, WorksForPairWithConst) {
1721 std::pair<const Wrapper<std::string>, int> p(Wrapper<std::string>("abc"), 1);
1722 ::std::stringstream ss;
1723 UniversalPrint(p, &ss);
1724 EXPECT_EQ("(Wrapper(\"abc\"), 1)", ss.str());
1725 }
1726
1727 TEST(UniversalPrintTest, WorksForCString) {
1728 const char* s1 = "abc";
1729 ::std::stringstream ss1;
1730 UniversalPrint(s1, &ss1);
1731 EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str()));
1732
1733 char* s2 = const_cast<char*>(s1);
1734 ::std::stringstream ss2;
1735 UniversalPrint(s2, &ss2);
1736 EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str()));
1737
1738 const char* s3 = nullptr;
1739 ::std::stringstream ss3;
1740 UniversalPrint(s3, &ss3);
1741 EXPECT_EQ("NULL", ss3.str());
1742 }
1743
1744 TEST(UniversalPrintTest, WorksForCharArray) {
1745 const char str[] = "\"Line\0 1\"\nLine 2";
1746 ::std::stringstream ss1;
1747 UniversalPrint(str, &ss1);
1748 EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str());
1749
1750 const char mutable_str[] = "\"Line\0 1\"\nLine 2";
1751 ::std::stringstream ss2;
1752 UniversalPrint(mutable_str, &ss2);
1753 EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str());
1754 }
1755
1756 TEST(UniversalPrintTest, IncompleteType) {
1757 struct Incomplete;
1758 char some_object = 0;
1759 EXPECT_EQ("(incomplete type)",
1760 PrintToString(reinterpret_cast<Incomplete&>(some_object)));
1761 }
1762
1763 TEST(UniversalPrintTest, SmartPointers) {
1764 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
1765 std::unique_ptr<int> p(new int(17));
1766 EXPECT_EQ("(ptr = " + PrintPointer(p.get()) + ", value = 17)",
1767 PrintToString(p));
1768 std::unique_ptr<int[]> p2(new int[2]);
1769 EXPECT_EQ("(" + PrintPointer(p2.get()) + ")", PrintToString(p2));
1770
1771 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
1772 std::shared_ptr<int> p3(new int(1979));
1773 EXPECT_EQ("(ptr = " + PrintPointer(p3.get()) + ", value = 1979)",
1774 PrintToString(p3));
1775 #if __cpp_lib_shared_ptr_arrays >= 201611L
1776 std::shared_ptr<int[]> p4(new int[2]);
1777 EXPECT_EQ("(" + PrintPointer(p4.get()) + ")", PrintToString(p4));
1778 #endif
1779
1780 // modifiers
1781 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
1782 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int>()));
1783 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int>()));
1784 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile const int>()));
1785 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int[]>()));
1786 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int[]>()));
1787 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int[]>()));
1788 EXPECT_EQ("(nullptr)",
1789 PrintToString(std::unique_ptr<volatile const int[]>()));
1790 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
1791 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int>()));
1792 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int>()));
1793 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile const int>()));
1794 #if __cpp_lib_shared_ptr_arrays >= 201611L
1795 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int[]>()));
1796 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int[]>()));
1797 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int[]>()));
1798 EXPECT_EQ("(nullptr)",
1799 PrintToString(std::shared_ptr<volatile const int[]>()));
1800 #endif
1801
1802 // void
1803 EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<void, void (*)(void*)>(
1804 nullptr, nullptr)));
1805 EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
1806 PrintToString(
__anon87d1ee4d0602(void*) 1807 std::unique_ptr<void, void (*)(void*)>(p.get(), [](void*) {})));
1808 EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<void>()));
1809 EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
__anon87d1ee4d0702(void*) 1810 PrintToString(std::shared_ptr<void>(p.get(), [](void*) {})));
1811 }
1812
1813 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
1814 Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
1815 EXPECT_EQ(0u, result.size());
1816 }
1817
1818 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
1819 Strings result = UniversalTersePrintTupleFieldsToStrings(
1820 ::std::make_tuple(1));
1821 ASSERT_EQ(1u, result.size());
1822 EXPECT_EQ("1", result[0]);
1823 }
1824
1825 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
1826 Strings result = UniversalTersePrintTupleFieldsToStrings(
1827 ::std::make_tuple(1, 'a'));
1828 ASSERT_EQ(2u, result.size());
1829 EXPECT_EQ("1", result[0]);
1830 EXPECT_EQ("'a' (97, 0x61)", result[1]);
1831 }
1832
1833 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
1834 const int n = 1;
1835 Strings result = UniversalTersePrintTupleFieldsToStrings(
1836 ::std::tuple<const int&, const char*>(n, "a"));
1837 ASSERT_EQ(2u, result.size());
1838 EXPECT_EQ("1", result[0]);
1839 EXPECT_EQ("\"a\"", result[1]);
1840 }
1841
1842 #if GTEST_INTERNAL_HAS_ANY
1843 class PrintAnyTest : public ::testing::Test {
1844 protected:
1845 template <typename T>
ExpectedTypeName()1846 static std::string ExpectedTypeName() {
1847 #if GTEST_HAS_RTTI
1848 return internal::GetTypeName<T>();
1849 #else
1850 return "<unknown_type>";
1851 #endif // GTEST_HAS_RTTI
1852 }
1853 };
1854
1855 TEST_F(PrintAnyTest, Empty) {
1856 internal::Any any;
1857 EXPECT_EQ("no value", PrintToString(any));
1858 }
1859
1860 TEST_F(PrintAnyTest, NonEmpty) {
1861 internal::Any any;
1862 constexpr int val1 = 10;
1863 const std::string val2 = "content";
1864
1865 any = val1;
1866 EXPECT_EQ("value of type " + ExpectedTypeName<int>(), PrintToString(any));
1867
1868 any = val2;
1869 EXPECT_EQ("value of type " + ExpectedTypeName<std::string>(),
1870 PrintToString(any));
1871 }
1872 #endif // GTEST_INTERNAL_HAS_ANY
1873
1874 #if GTEST_INTERNAL_HAS_OPTIONAL
1875 TEST(PrintOptionalTest, Basic) {
1876 internal::Optional<int> value;
1877 EXPECT_EQ("(nullopt)", PrintToString(value));
1878 value = {7};
1879 EXPECT_EQ("(7)", PrintToString(value));
1880 EXPECT_EQ("(1.1)", PrintToString(internal::Optional<double>{1.1}));
1881 EXPECT_EQ("(\"A\")", PrintToString(internal::Optional<std::string>{"A"}));
1882 }
1883 #endif // GTEST_INTERNAL_HAS_OPTIONAL
1884
1885 #if GTEST_INTERNAL_HAS_VARIANT
1886 struct NonPrintable {
1887 unsigned char contents = 17;
1888 };
1889
1890 TEST(PrintOneofTest, Basic) {
1891 using Type = internal::Variant<int, StreamableInGlobal, NonPrintable>;
1892 EXPECT_EQ("('int(index = 0)' with value 7)", PrintToString(Type(7)));
1893 EXPECT_EQ("('StreamableInGlobal(index = 1)' with value StreamableInGlobal)",
1894 PrintToString(Type(StreamableInGlobal{})));
1895 EXPECT_EQ(
1896 "('testing::gtest_printers_test::NonPrintable(index = 2)' with value "
1897 "1-byte object <11>)",
1898 PrintToString(Type(NonPrintable{})));
1899 }
1900 #endif // GTEST_INTERNAL_HAS_VARIANT
1901 namespace {
1902 class string_ref;
1903
1904 /**
1905 * This is a synthetic pointer to a fixed size string.
1906 */
1907 class string_ptr {
1908 public:
string_ptr(const char * data,size_t size)1909 string_ptr(const char* data, size_t size) : data_(data), size_(size) {}
1910
operator ++()1911 string_ptr& operator++() noexcept {
1912 data_ += size_;
1913 return *this;
1914 }
1915
1916 string_ref operator*() const noexcept;
1917
1918 private:
1919 const char* data_;
1920 size_t size_;
1921 };
1922
1923 /**
1924 * This is a synthetic reference of a fixed size string.
1925 */
1926 class string_ref {
1927 public:
string_ref(const char * data,size_t size)1928 string_ref(const char* data, size_t size) : data_(data), size_(size) {}
1929
operator &() const1930 string_ptr operator&() const noexcept { return {data_, size_}; } // NOLINT
1931
operator ==(const char * s) const1932 bool operator==(const char* s) const noexcept {
1933 if (size_ > 0 && data_[size_ - 1] != 0) {
1934 return std::string(data_, size_) == std::string(s);
1935 } else {
1936 return std::string(data_) == std::string(s);
1937 }
1938 }
1939
1940 private:
1941 const char* data_;
1942 size_t size_;
1943 };
1944
operator *() const1945 string_ref string_ptr::operator*() const noexcept { return {data_, size_}; }
1946
TEST(string_ref,compare)1947 TEST(string_ref, compare) {
1948 const char* s = "alex\0davidjohn\0";
1949 string_ptr ptr(s, 5);
1950 EXPECT_EQ(*ptr, "alex");
1951 EXPECT_TRUE(*ptr == "alex");
1952 ++ptr;
1953 EXPECT_EQ(*ptr, "david");
1954 EXPECT_TRUE(*ptr == "david");
1955 ++ptr;
1956 EXPECT_EQ(*ptr, "john");
1957 }
1958
1959 } // namespace
1960
1961 } // namespace gtest_printers_test
1962 } // namespace testing
1963