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 <ctype.h>
35 #include <limits.h>
36 #include <string.h>
37 #include <algorithm>
38 #include <deque>
39 #include <forward_list>
40 #include <list>
41 #include <map>
42 #include <set>
43 #include <sstream>
44 #include <string>
45 #include <unordered_map>
46 #include <unordered_set>
47 #include <utility>
48 #include <vector>
49
50 #include "gtest/gtest-printers.h"
51 #include "gtest/gtest.h"
52
53 // Some user-defined types for testing the universal value printer.
54
55 // An anonymous enum type.
56 enum AnonymousEnum { kAE1 = -1, kAE2 = 1 };
57
58 // An enum without a user-defined printer.
59 enum EnumWithoutPrinter { kEWP1 = -2, kEWP2 = 42 };
60
61 // An enum with a << operator.
62 enum EnumWithStreaming { kEWS1 = 10 };
63
operator <<(std::ostream & os,EnumWithStreaming e)64 std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
65 return os << (e == kEWS1 ? "kEWS1" : "invalid");
66 }
67
68 // An enum with a PrintTo() function.
69 enum EnumWithPrintTo { kEWPT1 = 1 };
70
PrintTo(EnumWithPrintTo e,std::ostream * os)71 void PrintTo(EnumWithPrintTo e, std::ostream* os) {
72 *os << (e == kEWPT1 ? "kEWPT1" : "invalid");
73 }
74
75 // A class implicitly convertible to BiggestInt.
76 class BiggestIntConvertible {
77 public:
operator ::testing::internal::BiggestInt() const78 operator ::testing::internal::BiggestInt() const { return 42; }
79 };
80
81 // A user-defined unprintable class template in the global namespace.
82 template <typename T>
83 class UnprintableTemplateInGlobal {
84 public:
UnprintableTemplateInGlobal()85 UnprintableTemplateInGlobal() : value_() {}
86
87 private:
88 T value_;
89 };
90
91 // A user-defined streamable type in the global namespace.
92 class StreamableInGlobal {
93 public:
~StreamableInGlobal()94 virtual ~StreamableInGlobal() {}
95 };
96
operator <<(::std::ostream & os,const StreamableInGlobal &)97 inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) {
98 os << "StreamableInGlobal";
99 }
100
operator <<(::std::ostream & os,const StreamableInGlobal *)101 void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) {
102 os << "StreamableInGlobal*";
103 }
104
105 namespace foo {
106
107 // A user-defined unprintable type in a user namespace.
108 class UnprintableInFoo {
109 public:
UnprintableInFoo()110 UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
z() const111 double z() const { return z_; }
112
113 private:
114 char xy_[8];
115 double z_;
116 };
117
118 // A user-defined printable type in a user-chosen namespace.
119 struct PrintableViaPrintTo {
PrintableViaPrintTofoo::PrintableViaPrintTo120 PrintableViaPrintTo() : value() {}
121 int value;
122 };
123
PrintTo(const PrintableViaPrintTo & x,::std::ostream * os)124 void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
125 *os << "PrintableViaPrintTo: " << x.value;
126 }
127
128 // A type with a user-defined << for printing its pointer.
129 struct PointerPrintable {};
130
operator <<(::std::ostream & os,const PointerPrintable *)131 ::std::ostream& operator<<(::std::ostream& os,
132 const PointerPrintable* /* x */) {
133 return os << "PointerPrintable*";
134 }
135
136 // A user-defined printable class template in a user-chosen namespace.
137 template <typename T>
138 class PrintableViaPrintToTemplate {
139 public:
PrintableViaPrintToTemplate(const T & a_value)140 explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
141
value() const142 const T& value() const { return value_; }
143
144 private:
145 T value_;
146 };
147
148 template <typename T>
PrintTo(const PrintableViaPrintToTemplate<T> & x,::std::ostream * os)149 void PrintTo(const PrintableViaPrintToTemplate<T>& x, ::std::ostream* os) {
150 *os << "PrintableViaPrintToTemplate: " << x.value();
151 }
152
153 // A user-defined streamable class template in a user namespace.
154 template <typename T>
155 class StreamableTemplateInFoo {
156 public:
StreamableTemplateInFoo()157 StreamableTemplateInFoo() : value_() {}
158
value() const159 const T& value() const { return value_; }
160
161 private:
162 T value_;
163 };
164
165 template <typename T>
operator <<(::std::ostream & os,const StreamableTemplateInFoo<T> & x)166 inline ::std::ostream& operator<<(::std::ostream& os,
167 const StreamableTemplateInFoo<T>& x) {
168 return os << "StreamableTemplateInFoo: " << x.value();
169 }
170
171 // A user-defined streamable but recursivly-defined container type in
172 // a user namespace, it mimics therefore std::filesystem::path or
173 // boost::filesystem::path.
174 class PathLike {
175 public:
176 struct iterator {
177 typedef PathLike value_type;
178
179 iterator& operator++();
180 PathLike& operator*();
181 };
182
183 using value_type = char;
184 using const_iterator = iterator;
185
PathLike()186 PathLike() {}
187
begin() const188 iterator begin() const { return iterator(); }
end() const189 iterator end() const { return iterator(); }
190
operator <<(::std::ostream & os,const PathLike &)191 friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) {
192 return os << "Streamable-PathLike";
193 }
194 };
195
196 } // namespace foo
197
198 namespace testing {
199 namespace gtest_printers_test {
200
201 using ::std::deque;
202 using ::std::list;
203 using ::std::make_pair;
204 using ::std::map;
205 using ::std::multimap;
206 using ::std::multiset;
207 using ::std::pair;
208 using ::std::set;
209 using ::std::vector;
210 using ::testing::PrintToString;
211 using ::testing::internal::FormatForComparisonFailureMessage;
212 using ::testing::internal::ImplicitCast_;
213 using ::testing::internal::NativeArray;
214 using ::testing::internal::RE;
215 using ::testing::internal::RelationToSourceReference;
216 using ::testing::internal::Strings;
217 using ::testing::internal::UniversalPrint;
218 using ::testing::internal::UniversalPrinter;
219 using ::testing::internal::UniversalTersePrint;
220 using ::testing::internal::UniversalTersePrintTupleFieldsToStrings;
221
222 // Prints a value to a string using the universal value printer. This
223 // is a helper for testing UniversalPrinter<T>::Print() for various types.
224 template <typename T>
Print(const T & value)225 std::string Print(const T& value) {
226 ::std::stringstream ss;
227 UniversalPrinter<T>::Print(value, &ss);
228 return ss.str();
229 }
230
231 // Prints a value passed by reference to a string, using the universal
232 // value printer. This is a helper for testing
233 // UniversalPrinter<T&>::Print() for various types.
234 template <typename T>
PrintByRef(const T & value)235 std::string PrintByRef(const T& value) {
236 ::std::stringstream ss;
237 UniversalPrinter<T&>::Print(value, &ss);
238 return ss.str();
239 }
240
241 // Tests printing various enum types.
242
TEST(PrintEnumTest,AnonymousEnum)243 TEST(PrintEnumTest, AnonymousEnum) {
244 EXPECT_EQ("-1", Print(kAE1));
245 EXPECT_EQ("1", Print(kAE2));
246 }
247
TEST(PrintEnumTest,EnumWithoutPrinter)248 TEST(PrintEnumTest, EnumWithoutPrinter) {
249 EXPECT_EQ("-2", Print(kEWP1));
250 EXPECT_EQ("42", Print(kEWP2));
251 }
252
TEST(PrintEnumTest,EnumWithStreaming)253 TEST(PrintEnumTest, EnumWithStreaming) {
254 EXPECT_EQ("kEWS1", Print(kEWS1));
255 EXPECT_EQ("invalid", Print(static_cast<EnumWithStreaming>(0)));
256 }
257
TEST(PrintEnumTest,EnumWithPrintTo)258 TEST(PrintEnumTest, EnumWithPrintTo) {
259 EXPECT_EQ("kEWPT1", Print(kEWPT1));
260 EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0)));
261 }
262
263 // Tests printing a class implicitly convertible to BiggestInt.
264
TEST(PrintClassTest,BiggestIntConvertible)265 TEST(PrintClassTest, BiggestIntConvertible) {
266 EXPECT_EQ("42", Print(BiggestIntConvertible()));
267 }
268
269 // Tests printing various char types.
270
271 // char.
TEST(PrintCharTest,PlainChar)272 TEST(PrintCharTest, PlainChar) {
273 EXPECT_EQ("'\\0'", Print('\0'));
274 EXPECT_EQ("'\\'' (39, 0x27)", Print('\''));
275 EXPECT_EQ("'\"' (34, 0x22)", Print('"'));
276 EXPECT_EQ("'?' (63, 0x3F)", Print('?'));
277 EXPECT_EQ("'\\\\' (92, 0x5C)", Print('\\'));
278 EXPECT_EQ("'\\a' (7)", Print('\a'));
279 EXPECT_EQ("'\\b' (8)", Print('\b'));
280 EXPECT_EQ("'\\f' (12, 0xC)", Print('\f'));
281 EXPECT_EQ("'\\n' (10, 0xA)", Print('\n'));
282 EXPECT_EQ("'\\r' (13, 0xD)", Print('\r'));
283 EXPECT_EQ("'\\t' (9)", Print('\t'));
284 EXPECT_EQ("'\\v' (11, 0xB)", Print('\v'));
285 EXPECT_EQ("'\\x7F' (127)", Print('\x7F'));
286 EXPECT_EQ("'\\xFF' (255)", Print('\xFF'));
287 EXPECT_EQ("' ' (32, 0x20)", Print(' '));
288 EXPECT_EQ("'a' (97, 0x61)", Print('a'));
289 }
290
291 // signed char.
TEST(PrintCharTest,SignedChar)292 TEST(PrintCharTest, SignedChar) {
293 EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0')));
294 EXPECT_EQ("'\\xCE' (-50)", Print(static_cast<signed char>(-50)));
295 }
296
297 // unsigned char.
TEST(PrintCharTest,UnsignedChar)298 TEST(PrintCharTest, UnsignedChar) {
299 EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0')));
300 EXPECT_EQ("'b' (98, 0x62)", Print(static_cast<unsigned char>('b')));
301 }
302
303 // Tests printing other simple, built-in types.
304
305 // bool.
TEST(PrintBuiltInTypeTest,Bool)306 TEST(PrintBuiltInTypeTest, Bool) {
307 EXPECT_EQ("false", Print(false));
308 EXPECT_EQ("true", Print(true));
309 }
310
311 // wchar_t.
TEST(PrintBuiltInTypeTest,Wchar_t)312 TEST(PrintBuiltInTypeTest, Wchar_t) {
313 EXPECT_EQ("L'\\0'", Print(L'\0'));
314 EXPECT_EQ("L'\\'' (39, 0x27)", Print(L'\''));
315 EXPECT_EQ("L'\"' (34, 0x22)", Print(L'"'));
316 EXPECT_EQ("L'?' (63, 0x3F)", Print(L'?'));
317 EXPECT_EQ("L'\\\\' (92, 0x5C)", Print(L'\\'));
318 EXPECT_EQ("L'\\a' (7)", Print(L'\a'));
319 EXPECT_EQ("L'\\b' (8)", Print(L'\b'));
320 EXPECT_EQ("L'\\f' (12, 0xC)", Print(L'\f'));
321 EXPECT_EQ("L'\\n' (10, 0xA)", Print(L'\n'));
322 EXPECT_EQ("L'\\r' (13, 0xD)", Print(L'\r'));
323 EXPECT_EQ("L'\\t' (9)", Print(L'\t'));
324 EXPECT_EQ("L'\\v' (11, 0xB)", Print(L'\v'));
325 EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F'));
326 EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF'));
327 EXPECT_EQ("L' ' (32, 0x20)", Print(L' '));
328 EXPECT_EQ("L'a' (97, 0x61)", Print(L'a'));
329 EXPECT_EQ("L'\\x576' (1398)", Print(static_cast<wchar_t>(0x576)));
330 EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast<wchar_t>(0xC74D)));
331 }
332
333 // Test that Int64 provides more storage than wchar_t.
TEST(PrintTypeSizeTest,Wchar_t)334 TEST(PrintTypeSizeTest, Wchar_t) {
335 EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64));
336 }
337
338 // Various integer types.
TEST(PrintBuiltInTypeTest,Integer)339 TEST(PrintBuiltInTypeTest, Integer) {
340 EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255))); // uint8
341 EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128))); // int8
342 EXPECT_EQ("65535", Print(USHRT_MAX)); // uint16
343 EXPECT_EQ("-32768", Print(SHRT_MIN)); // int16
344 EXPECT_EQ("4294967295", Print(UINT_MAX)); // uint32
345 EXPECT_EQ("-2147483648", Print(INT_MIN)); // int32
346 EXPECT_EQ("18446744073709551615",
347 Print(static_cast<testing::internal::UInt64>(-1))); // uint64
348 EXPECT_EQ("-9223372036854775808",
349 Print(static_cast<testing::internal::Int64>(1) << 63)); // int64
350 }
351
352 // Size types.
TEST(PrintBuiltInTypeTest,Size_t)353 TEST(PrintBuiltInTypeTest, Size_t) {
354 EXPECT_EQ("1", Print(sizeof('a'))); // size_t.
355 #if !GTEST_OS_WINDOWS
356 // Windows has no ssize_t type.
357 EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2))); // ssize_t.
358 #endif // !GTEST_OS_WINDOWS
359 }
360
361 // Floating-points.
TEST(PrintBuiltInTypeTest,FloatingPoints)362 TEST(PrintBuiltInTypeTest, FloatingPoints) {
363 EXPECT_EQ("1.5", Print(1.5f)); // float
364 EXPECT_EQ("-2.5", Print(-2.5)); // double
365 }
366
367 // Since ::std::stringstream::operator<<(const void *) formats the pointer
368 // output differently with different compilers, we have to create the expected
369 // output first and use it as our expectation.
PrintPointer(const void * p)370 static std::string PrintPointer(const void* p) {
371 ::std::stringstream expected_result_stream;
372 expected_result_stream << p;
373 return expected_result_stream.str();
374 }
375
376 // Tests printing C strings.
377
378 // const char*.
TEST(PrintCStringTest,Const)379 TEST(PrintCStringTest, Const) {
380 const char* p = "World";
381 EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p));
382 }
383
384 // char*.
TEST(PrintCStringTest,NonConst)385 TEST(PrintCStringTest, NonConst) {
386 char p[] = "Hi";
387 EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"",
388 Print(static_cast<char*>(p)));
389 }
390
391 // NULL C string.
TEST(PrintCStringTest,Null)392 TEST(PrintCStringTest, Null) {
393 const char* p = nullptr;
394 EXPECT_EQ("NULL", Print(p));
395 }
396
397 // Tests that C strings are escaped properly.
TEST(PrintCStringTest,EscapesProperly)398 TEST(PrintCStringTest, EscapesProperly) {
399 const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
400 EXPECT_EQ(PrintPointer(p) +
401 " pointing to \"'\\\"?\\\\\\a\\b\\f"
402 "\\n\\r\\t\\v\\x7F\\xFF a\"",
403 Print(p));
404 }
405
406 // MSVC compiler can be configured to define whar_t as a typedef
407 // of unsigned short. Defining an overload for const wchar_t* in that case
408 // would cause pointers to unsigned shorts be printed as wide strings,
409 // possibly accessing more memory than intended and causing invalid
410 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
411 // wchar_t is implemented as a native type.
412 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
413
414 // const wchar_t*.
TEST(PrintWideCStringTest,Const)415 TEST(PrintWideCStringTest, Const) {
416 const wchar_t* p = L"World";
417 EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p));
418 }
419
420 // wchar_t*.
TEST(PrintWideCStringTest,NonConst)421 TEST(PrintWideCStringTest, NonConst) {
422 wchar_t p[] = L"Hi";
423 EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"",
424 Print(static_cast<wchar_t*>(p)));
425 }
426
427 // NULL wide C string.
TEST(PrintWideCStringTest,Null)428 TEST(PrintWideCStringTest, Null) {
429 const wchar_t* p = nullptr;
430 EXPECT_EQ("NULL", Print(p));
431 }
432
433 // Tests that wide C strings are escaped properly.
TEST(PrintWideCStringTest,EscapesProperly)434 TEST(PrintWideCStringTest, EscapesProperly) {
435 const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b',
436 '\f', '\n', '\r', '\t', '\v', 0xD3,
437 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'};
438 EXPECT_EQ(PrintPointer(s) +
439 " pointing to L\"'\\\"?\\\\\\a\\b\\f"
440 "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
441 Print(static_cast<const wchar_t*>(s)));
442 }
443 #endif // native wchar_t
444
445 // Tests printing pointers to other char types.
446
447 // signed char*.
TEST(PrintCharPointerTest,SignedChar)448 TEST(PrintCharPointerTest, SignedChar) {
449 signed char* p = reinterpret_cast<signed char*>(0x1234);
450 EXPECT_EQ(PrintPointer(p), Print(p));
451 p = nullptr;
452 EXPECT_EQ("NULL", Print(p));
453 }
454
455 // const signed char*.
TEST(PrintCharPointerTest,ConstSignedChar)456 TEST(PrintCharPointerTest, ConstSignedChar) {
457 signed char* p = reinterpret_cast<signed char*>(0x1234);
458 EXPECT_EQ(PrintPointer(p), Print(p));
459 p = nullptr;
460 EXPECT_EQ("NULL", Print(p));
461 }
462
463 // unsigned char*.
TEST(PrintCharPointerTest,UnsignedChar)464 TEST(PrintCharPointerTest, UnsignedChar) {
465 unsigned char* p = reinterpret_cast<unsigned char*>(0x1234);
466 EXPECT_EQ(PrintPointer(p), Print(p));
467 p = nullptr;
468 EXPECT_EQ("NULL", Print(p));
469 }
470
471 // const unsigned char*.
TEST(PrintCharPointerTest,ConstUnsignedChar)472 TEST(PrintCharPointerTest, ConstUnsignedChar) {
473 const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234);
474 EXPECT_EQ(PrintPointer(p), Print(p));
475 p = nullptr;
476 EXPECT_EQ("NULL", Print(p));
477 }
478
479 // Tests printing pointers to simple, built-in types.
480
481 // bool*.
TEST(PrintPointerToBuiltInTypeTest,Bool)482 TEST(PrintPointerToBuiltInTypeTest, Bool) {
483 bool* p = reinterpret_cast<bool*>(0xABCD);
484 EXPECT_EQ(PrintPointer(p), Print(p));
485 p = nullptr;
486 EXPECT_EQ("NULL", Print(p));
487 }
488
489 // void*.
TEST(PrintPointerToBuiltInTypeTest,Void)490 TEST(PrintPointerToBuiltInTypeTest, Void) {
491 void* p = reinterpret_cast<void*>(0xABCD);
492 EXPECT_EQ(PrintPointer(p), Print(p));
493 p = nullptr;
494 EXPECT_EQ("NULL", Print(p));
495 }
496
497 // const void*.
TEST(PrintPointerToBuiltInTypeTest,ConstVoid)498 TEST(PrintPointerToBuiltInTypeTest, ConstVoid) {
499 const void* p = reinterpret_cast<const void*>(0xABCD);
500 EXPECT_EQ(PrintPointer(p), Print(p));
501 p = nullptr;
502 EXPECT_EQ("NULL", Print(p));
503 }
504
505 // Tests printing pointers to pointers.
TEST(PrintPointerToPointerTest,IntPointerPointer)506 TEST(PrintPointerToPointerTest, IntPointerPointer) {
507 int** p = reinterpret_cast<int**>(0xABCD);
508 EXPECT_EQ(PrintPointer(p), Print(p));
509 p = nullptr;
510 EXPECT_EQ("NULL", Print(p));
511 }
512
513 // Tests printing (non-member) function pointers.
514
MyFunction(int)515 void MyFunction(int /* n */) {}
516
TEST(PrintPointerTest,NonMemberFunctionPointer)517 TEST(PrintPointerTest, NonMemberFunctionPointer) {
518 // We cannot directly cast &MyFunction to const void* because the
519 // standard disallows casting between pointers to functions and
520 // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
521 // this limitation.
522 EXPECT_EQ(PrintPointer(reinterpret_cast<const void*>(
523 reinterpret_cast<internal::BiggestInt>(&MyFunction))),
524 Print(&MyFunction));
525 int (*p)(bool) = NULL; // NOLINT
526 EXPECT_EQ("NULL", Print(p));
527 }
528
529 // An assertion predicate determining whether a one string is a prefix for
530 // another.
531 template <typename StringType>
HasPrefix(const StringType & str,const StringType & prefix)532 AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
533 if (str.find(prefix, 0) == 0) return AssertionSuccess();
534
535 const bool is_wide_string = sizeof(prefix[0]) > 1;
536 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
537 return AssertionFailure() << begin_string_quote << prefix
538 << "\" is not a prefix of " << begin_string_quote
539 << str << "\"\n";
540 }
541
542 // Tests printing member variable pointers. Although they are called
543 // pointers, they don't point to a location in the address space.
544 // Their representation is implementation-defined. Thus they will be
545 // printed as raw bytes.
546
547 struct Foo {
548 public:
~Footesting::gtest_printers_test::Foo549 virtual ~Foo() {}
MyMethodtesting::gtest_printers_test::Foo550 int MyMethod(char x) { return x + 1; }
MyVirtualMethodtesting::gtest_printers_test::Foo551 virtual char MyVirtualMethod(int /* n */) { return 'a'; }
552
553 int value;
554 };
555
TEST(PrintPointerTest,MemberVariablePointer)556 TEST(PrintPointerTest, MemberVariablePointer) {
557 EXPECT_TRUE(HasPrefix(Print(&Foo::value),
558 Print(sizeof(&Foo::value)) + "-byte object "));
559 int Foo::*p = NULL; // NOLINT
560 EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
561 }
562
563 // Tests printing member function pointers. Although they are called
564 // pointers, they don't point to a location in the address space.
565 // Their representation is implementation-defined. Thus they will be
566 // printed as raw bytes.
TEST(PrintPointerTest,MemberFunctionPointer)567 TEST(PrintPointerTest, MemberFunctionPointer) {
568 EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod),
569 Print(sizeof(&Foo::MyMethod)) + "-byte object "));
570 EXPECT_TRUE(
571 HasPrefix(Print(&Foo::MyVirtualMethod),
572 Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
573 int (Foo::*p)(char) = NULL; // NOLINT
574 EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
575 }
576
577 // Tests printing C arrays.
578
579 // The difference between this and Print() is that it ensures that the
580 // argument is a reference to an array.
581 template <typename T, size_t N>
PrintArrayHelper(T (& a)[N])582 std::string PrintArrayHelper(T (&a)[N]) {
583 return Print(a);
584 }
585
586 // One-dimensional array.
TEST(PrintArrayTest,OneDimensionalArray)587 TEST(PrintArrayTest, OneDimensionalArray) {
588 int a[5] = {1, 2, 3, 4, 5};
589 EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
590 }
591
592 // Two-dimensional array.
TEST(PrintArrayTest,TwoDimensionalArray)593 TEST(PrintArrayTest, TwoDimensionalArray) {
594 int a[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}};
595 EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
596 }
597
598 // Array of const elements.
TEST(PrintArrayTest,ConstArray)599 TEST(PrintArrayTest, ConstArray) {
600 const bool a[1] = {false};
601 EXPECT_EQ("{ false }", PrintArrayHelper(a));
602 }
603
604 // char array without terminating NUL.
TEST(PrintArrayTest,CharArrayWithNoTerminatingNul)605 TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {
606 // Array a contains '\0' in the middle and doesn't end with '\0'.
607 char a[] = {'H', '\0', 'i'};
608 EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
609 }
610
611 // const char array with terminating NUL.
TEST(PrintArrayTest,ConstCharArrayWithTerminatingNul)612 TEST(PrintArrayTest, ConstCharArrayWithTerminatingNul) {
613 const char a[] = "\0Hi";
614 EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a));
615 }
616
617 // const wchar_t array without terminating NUL.
TEST(PrintArrayTest,WCharArrayWithNoTerminatingNul)618 TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) {
619 // Array a contains '\0' in the middle and doesn't end with '\0'.
620 const wchar_t a[] = {L'H', L'\0', L'i'};
621 EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
622 }
623
624 // wchar_t array with terminating NUL.
TEST(PrintArrayTest,WConstCharArrayWithTerminatingNul)625 TEST(PrintArrayTest, WConstCharArrayWithTerminatingNul) {
626 const wchar_t a[] = L"\0Hi";
627 EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a));
628 }
629
630 // Array of objects.
TEST(PrintArrayTest,ObjectArray)631 TEST(PrintArrayTest, ObjectArray) {
632 std::string a[3] = {"Hi", "Hello", "Ni hao"};
633 EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a));
634 }
635
636 // Array with many elements.
TEST(PrintArrayTest,BigArray)637 TEST(PrintArrayTest, BigArray) {
638 int a[100] = {1, 2, 3};
639 EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }",
640 PrintArrayHelper(a));
641 }
642
643 // Tests printing ::string and ::std::string.
644
645 // ::std::string.
TEST(PrintStringTest,StringInStdNamespace)646 TEST(PrintStringTest, StringInStdNamespace) {
647 const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
648 const ::std::string str(s, sizeof(s));
649 EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
650 Print(str));
651 }
652
TEST(PrintStringTest,StringAmbiguousHex)653 TEST(PrintStringTest, StringAmbiguousHex) {
654 // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of:
655 // '\x6', '\x6B', or '\x6BA'.
656
657 // a hex escaping sequence following by a decimal digit
658 EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12"
659 "3")));
660 // a hex escaping sequence following by a hex digit (lower-case)
661 EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6"
662 "bananas")));
663 // a hex escaping sequence following by a hex digit (upper-case)
664 EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6"
665 "BANANA")));
666 // a hex escaping sequence following by a non-xdigit
667 EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
668 }
669
670 // Tests printing ::std::wstring.
671 #if GTEST_HAS_STD_WSTRING
672 // ::std::wstring.
TEST(PrintWideStringTest,StringInStdNamespace)673 TEST(PrintWideStringTest, StringInStdNamespace) {
674 const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
675 const ::std::wstring str(s, sizeof(s) / sizeof(wchar_t));
676 EXPECT_EQ(
677 "L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
678 "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
679 Print(str));
680 }
681
TEST(PrintWideStringTest,StringAmbiguousHex)682 TEST(PrintWideStringTest, StringAmbiguousHex) {
683 // same for wide strings.
684 EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12"
685 L"3")));
686 EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", Print(::std::wstring(L"mm\x6"
687 L"bananas")));
688 EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", Print(::std::wstring(L"NOM\x6"
689 L"BANANA")));
690 EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
691 }
692 #endif // GTEST_HAS_STD_WSTRING
693
694 // Tests printing types that support generic streaming (i.e. streaming
695 // to std::basic_ostream<Char, CharTraits> for any valid Char and
696 // CharTraits types).
697
698 // Tests printing a non-template type that supports generic streaming.
699
700 class AllowsGenericStreaming {};
701
702 template <typename Char, typename CharTraits>
operator <<(std::basic_ostream<Char,CharTraits> & os,const AllowsGenericStreaming &)703 std::basic_ostream<Char, CharTraits>& operator<<(
704 std::basic_ostream<Char, CharTraits>& os,
705 const AllowsGenericStreaming& /* a */) {
706 return os << "AllowsGenericStreaming";
707 }
708
TEST(PrintTypeWithGenericStreamingTest,NonTemplateType)709 TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) {
710 AllowsGenericStreaming a;
711 EXPECT_EQ("AllowsGenericStreaming", Print(a));
712 }
713
714 // Tests printing a template type that supports generic streaming.
715
716 template <typename T>
717 class AllowsGenericStreamingTemplate {};
718
719 template <typename Char, typename CharTraits, typename T>
operator <<(std::basic_ostream<Char,CharTraits> & os,const AllowsGenericStreamingTemplate<T> &)720 std::basic_ostream<Char, CharTraits>& operator<<(
721 std::basic_ostream<Char, CharTraits>& os,
722 const AllowsGenericStreamingTemplate<T>& /* a */) {
723 return os << "AllowsGenericStreamingTemplate";
724 }
725
TEST(PrintTypeWithGenericStreamingTest,TemplateType)726 TEST(PrintTypeWithGenericStreamingTest, TemplateType) {
727 AllowsGenericStreamingTemplate<int> a;
728 EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a));
729 }
730
731 // Tests printing a type that supports generic streaming and can be
732 // implicitly converted to another printable type.
733
734 template <typename T>
735 class AllowsGenericStreamingAndImplicitConversionTemplate {
736 public:
operator bool() const737 operator bool() const { return false; }
738 };
739
740 template <typename Char, typename CharTraits, typename T>
operator <<(std::basic_ostream<Char,CharTraits> & os,const AllowsGenericStreamingAndImplicitConversionTemplate<T> &)741 std::basic_ostream<Char, CharTraits>& operator<<(
742 std::basic_ostream<Char, CharTraits>& os,
743 const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) {
744 return os << "AllowsGenericStreamingAndImplicitConversionTemplate";
745 }
746
TEST(PrintTypeWithGenericStreamingTest,TypeImplicitlyConvertible)747 TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
748 AllowsGenericStreamingAndImplicitConversionTemplate<int> a;
749 EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
750 }
751
752 #if GTEST_HAS_ABSL
753
754 // Tests printing ::absl::string_view.
755
TEST(PrintStringViewTest,SimpleStringView)756 TEST(PrintStringViewTest, SimpleStringView) {
757 const ::absl::string_view sp = "Hello";
758 EXPECT_EQ("\"Hello\"", Print(sp));
759 }
760
TEST(PrintStringViewTest,UnprintableCharacters)761 TEST(PrintStringViewTest, UnprintableCharacters) {
762 const char str[] = "NUL (\0) and \r\t";
763 const ::absl::string_view sp(str, sizeof(str) - 1);
764 EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
765 }
766
767 #endif // GTEST_HAS_ABSL
768
769 // Tests printing STL containers.
770
TEST(PrintStlContainerTest,EmptyDeque)771 TEST(PrintStlContainerTest, EmptyDeque) {
772 deque<char> empty;
773 EXPECT_EQ("{}", Print(empty));
774 }
775
TEST(PrintStlContainerTest,NonEmptyDeque)776 TEST(PrintStlContainerTest, NonEmptyDeque) {
777 deque<int> non_empty;
778 non_empty.push_back(1);
779 non_empty.push_back(3);
780 EXPECT_EQ("{ 1, 3 }", Print(non_empty));
781 }
782
TEST(PrintStlContainerTest,OneElementHashMap)783 TEST(PrintStlContainerTest, OneElementHashMap) {
784 ::std::unordered_map<int, char> map1;
785 map1[1] = 'a';
786 EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1));
787 }
788
TEST(PrintStlContainerTest,HashMultiMap)789 TEST(PrintStlContainerTest, HashMultiMap) {
790 ::std::unordered_multimap<int, bool> map1;
791 map1.insert(make_pair(5, true));
792 map1.insert(make_pair(5, false));
793
794 // Elements of hash_multimap can be printed in any order.
795 const std::string result = Print(map1);
796 EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
797 result == "{ (5, false), (5, true) }")
798 << " where Print(map1) returns \"" << result << "\".";
799 }
800
TEST(PrintStlContainerTest,HashSet)801 TEST(PrintStlContainerTest, HashSet) {
802 ::std::unordered_set<int> set1;
803 set1.insert(1);
804 EXPECT_EQ("{ 1 }", Print(set1));
805 }
806
TEST(PrintStlContainerTest,HashMultiSet)807 TEST(PrintStlContainerTest, HashMultiSet) {
808 const int kSize = 5;
809 int a[kSize] = {1, 1, 2, 5, 1};
810 ::std::unordered_multiset<int> set1(a, a + kSize);
811
812 // Elements of hash_multiset can be printed in any order.
813 const std::string result = Print(set1);
814 const std::string expected_pattern = "{ d, d, d, d, d }"; // d means a digit.
815
816 // Verifies the result matches the expected pattern; also extracts
817 // the numbers in the result.
818 ASSERT_EQ(expected_pattern.length(), result.length());
819 std::vector<int> numbers;
820 for (size_t i = 0; i != result.length(); i++) {
821 if (expected_pattern[i] == 'd') {
822 ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
823 numbers.push_back(result[i] - '0');
824 } else {
825 EXPECT_EQ(expected_pattern[i], result[i]) << " where result is "
826 << result;
827 }
828 }
829
830 // Makes sure the result contains the right numbers.
831 std::sort(numbers.begin(), numbers.end());
832 std::sort(a, a + kSize);
833 EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
834 }
835
TEST(PrintStlContainerTest,List)836 TEST(PrintStlContainerTest, List) {
837 const std::string a[] = {"hello", "world"};
838 const list<std::string> strings(a, a + 2);
839 EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings));
840 }
841
TEST(PrintStlContainerTest,Map)842 TEST(PrintStlContainerTest, Map) {
843 map<int, bool> map1;
844 map1[1] = true;
845 map1[5] = false;
846 map1[3] = true;
847 EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1));
848 }
849
TEST(PrintStlContainerTest,MultiMap)850 TEST(PrintStlContainerTest, MultiMap) {
851 multimap<bool, int> map1;
852 // The make_pair template function would deduce the type as
853 // pair<bool, int> here, and since the key part in a multimap has to
854 // be constant, without a templated ctor in the pair class (as in
855 // libCstd on Solaris), make_pair call would fail to compile as no
856 // implicit conversion is found. Thus explicit typename is used
857 // here instead.
858 map1.insert(pair<const bool, int>(true, 0));
859 map1.insert(pair<const bool, int>(true, 1));
860 map1.insert(pair<const bool, int>(false, 2));
861 EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1));
862 }
863
TEST(PrintStlContainerTest,Set)864 TEST(PrintStlContainerTest, Set) {
865 const unsigned int a[] = {3, 0, 5};
866 set<unsigned int> set1(a, a + 3);
867 EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
868 }
869
TEST(PrintStlContainerTest,MultiSet)870 TEST(PrintStlContainerTest, MultiSet) {
871 const int a[] = {1, 1, 2, 5, 1};
872 multiset<int> set1(a, a + 5);
873 EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
874 }
875
TEST(PrintStlContainerTest,SinglyLinkedList)876 TEST(PrintStlContainerTest, SinglyLinkedList) {
877 int a[] = {9, 2, 8};
878 const std::forward_list<int> ints(a, a + 3);
879 EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
880 }
881
TEST(PrintStlContainerTest,Pair)882 TEST(PrintStlContainerTest, Pair) {
883 pair<const bool, int> p(true, 5);
884 EXPECT_EQ("(true, 5)", Print(p));
885 }
886
TEST(PrintStlContainerTest,Vector)887 TEST(PrintStlContainerTest, Vector) {
888 vector<int> v;
889 v.push_back(1);
890 v.push_back(2);
891 EXPECT_EQ("{ 1, 2 }", Print(v));
892 }
893
TEST(PrintStlContainerTest,LongSequence)894 TEST(PrintStlContainerTest, LongSequence) {
895 const int a[100] = {1, 2, 3};
896 const vector<int> v(a, a + 100);
897 EXPECT_EQ(
898 "{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
899 "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }",
900 Print(v));
901 }
902
TEST(PrintStlContainerTest,NestedContainer)903 TEST(PrintStlContainerTest, NestedContainer) {
904 const int a1[] = {1, 2};
905 const int a2[] = {3, 4, 5};
906 const list<int> l1(a1, a1 + 2);
907 const list<int> l2(a2, a2 + 3);
908
909 vector<list<int> > v;
910 v.push_back(l1);
911 v.push_back(l2);
912 EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
913 }
914
TEST(PrintStlContainerTest,OneDimensionalNativeArray)915 TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
916 const int a[3] = {1, 2, 3};
917 NativeArray<int> b(a, 3, RelationToSourceReference());
918 EXPECT_EQ("{ 1, 2, 3 }", Print(b));
919 }
920
TEST(PrintStlContainerTest,TwoDimensionalNativeArray)921 TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
922 const int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
923 NativeArray<int[3]> b(a, 2, RelationToSourceReference());
924 EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
925 }
926
927 // Tests that a class named iterator isn't treated as a container.
928
929 struct iterator {
930 char x;
931 };
932
TEST(PrintStlContainerTest,Iterator)933 TEST(PrintStlContainerTest, Iterator) {
934 iterator it = {};
935 EXPECT_EQ("1-byte object <00>", Print(it));
936 }
937
938 // Tests that a class named const_iterator isn't treated as a container.
939
940 struct const_iterator {
941 char x;
942 };
943
TEST(PrintStlContainerTest,ConstIterator)944 TEST(PrintStlContainerTest, ConstIterator) {
945 const_iterator it = {};
946 EXPECT_EQ("1-byte object <00>", Print(it));
947 }
948
949 // Tests printing ::std::tuples.
950
951 // Tuples of various arities.
TEST(PrintStdTupleTest,VariousSizes)952 TEST(PrintStdTupleTest, VariousSizes) {
953 ::std::tuple<> t0;
954 EXPECT_EQ("()", Print(t0));
955
956 ::std::tuple<int> t1(5);
957 EXPECT_EQ("(5)", Print(t1));
958
959 ::std::tuple<char, bool> t2('a', true);
960 EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
961
962 ::std::tuple<bool, int, int> t3(false, 2, 3);
963 EXPECT_EQ("(false, 2, 3)", Print(t3));
964
965 ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4);
966 EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
967
968 const char* const str = "8";
969 ::std::tuple<bool, char, short, testing::internal::Int32, // NOLINT
970 testing::internal::Int64, float, double, const char*, void*,
971 std::string>
972 t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT
973 nullptr, "10");
974 EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
975 " pointing to \"8\", NULL, \"10\")",
976 Print(t10));
977 }
978
979 // Nested tuples.
TEST(PrintStdTupleTest,NestedTuple)980 TEST(PrintStdTupleTest, NestedTuple) {
981 ::std::tuple< ::std::tuple<int, bool>, char> nested(
982 ::std::make_tuple(5, true), 'a');
983 EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
984 }
985
TEST(PrintNullptrT,Basic)986 TEST(PrintNullptrT, Basic) { EXPECT_EQ("(nullptr)", Print(nullptr)); }
987
TEST(PrintReferenceWrapper,Printable)988 TEST(PrintReferenceWrapper, Printable) {
989 int x = 5;
990 EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::ref(x)));
991 EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::cref(x)));
992 }
993
TEST(PrintReferenceWrapper,Unprintable)994 TEST(PrintReferenceWrapper, Unprintable) {
995 ::foo::UnprintableInFoo up;
996 EXPECT_EQ(
997 "@" + PrintPointer(&up) +
998 " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
999 Print(std::ref(up)));
1000 EXPECT_EQ(
1001 "@" + PrintPointer(&up) +
1002 " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1003 Print(std::cref(up)));
1004 }
1005
1006 // Tests printing user-defined unprintable types.
1007
1008 // Unprintable types in the global namespace.
TEST(PrintUnprintableTypeTest,InGlobalNamespace)1009 TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
1010 EXPECT_EQ("1-byte object <00>", Print(UnprintableTemplateInGlobal<char>()));
1011 }
1012
1013 // Unprintable types in a user namespace.
TEST(PrintUnprintableTypeTest,InUserNamespace)1014 TEST(PrintUnprintableTypeTest, InUserNamespace) {
1015 EXPECT_EQ("16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1016 Print(::foo::UnprintableInFoo()));
1017 }
1018
1019 // Unprintable types are that too big to be printed completely.
1020
1021 struct Big {
Bigtesting::gtest_printers_test::Big1022 Big() { memset(array, 0, sizeof(array)); }
1023 char array[257];
1024 };
1025
TEST(PrintUnpritableTypeTest,BigObject)1026 TEST(PrintUnpritableTypeTest, BigObject) {
1027 EXPECT_EQ(
1028 "257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
1029 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1030 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1031 "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
1032 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1033 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1034 "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
1035 Print(Big()));
1036 }
1037
1038 // Tests printing user-defined streamable types.
1039
1040 // Streamable types in the global namespace.
TEST(PrintStreamableTypeTest,InGlobalNamespace)1041 TEST(PrintStreamableTypeTest, InGlobalNamespace) {
1042 StreamableInGlobal x;
1043 EXPECT_EQ("StreamableInGlobal", Print(x));
1044 EXPECT_EQ("StreamableInGlobal*", Print(&x));
1045 }
1046
1047 // Printable template types in a user namespace.
TEST(PrintStreamableTypeTest,TemplateTypeInUserNamespace)1048 TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
1049 EXPECT_EQ("StreamableTemplateInFoo: 0",
1050 Print(::foo::StreamableTemplateInFoo<int>()));
1051 }
1052
1053 // Tests printing a user-defined recursive container type that has a <<
1054 // operator.
TEST(PrintStreamableTypeTest,PathLikeInUserNamespace)1055 TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
1056 ::foo::PathLike x;
1057 EXPECT_EQ("Streamable-PathLike", Print(x));
1058 const ::foo::PathLike cx;
1059 EXPECT_EQ("Streamable-PathLike", Print(cx));
1060 }
1061
1062 // Tests printing user-defined types that have a PrintTo() function.
TEST(PrintPrintableTypeTest,InUserNamespace)1063 TEST(PrintPrintableTypeTest, InUserNamespace) {
1064 EXPECT_EQ("PrintableViaPrintTo: 0", Print(::foo::PrintableViaPrintTo()));
1065 }
1066
1067 // Tests printing a pointer to a user-defined type that has a <<
1068 // operator for its pointer.
TEST(PrintPrintableTypeTest,PointerInUserNamespace)1069 TEST(PrintPrintableTypeTest, PointerInUserNamespace) {
1070 ::foo::PointerPrintable x;
1071 EXPECT_EQ("PointerPrintable*", Print(&x));
1072 }
1073
1074 // Tests printing user-defined class template that have a PrintTo() function.
TEST(PrintPrintableTypeTest,TemplateInUserNamespace)1075 TEST(PrintPrintableTypeTest, TemplateInUserNamespace) {
1076 EXPECT_EQ("PrintableViaPrintToTemplate: 5",
1077 Print(::foo::PrintableViaPrintToTemplate<int>(5)));
1078 }
1079
1080 // Tests that the universal printer prints both the address and the
1081 // value of a reference.
TEST(PrintReferenceTest,PrintsAddressAndValue)1082 TEST(PrintReferenceTest, PrintsAddressAndValue) {
1083 int n = 5;
1084 EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
1085
1086 int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
1087 EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
1088 PrintByRef(a));
1089
1090 const ::foo::UnprintableInFoo x;
1091 EXPECT_EQ("@" + PrintPointer(&x) +
1092 " 16-byte object "
1093 "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1094 PrintByRef(x));
1095 }
1096
1097 // Tests that the universal printer prints a function pointer passed by
1098 // reference.
TEST(PrintReferenceTest,HandlesFunctionPointer)1099 TEST(PrintReferenceTest, HandlesFunctionPointer) {
1100 void (*fp)(int n) = &MyFunction;
1101 const std::string fp_pointer_string =
1102 PrintPointer(reinterpret_cast<const void*>(&fp));
1103 // We cannot directly cast &MyFunction to const void* because the
1104 // standard disallows casting between pointers to functions and
1105 // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
1106 // this limitation.
1107 const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(
1108 reinterpret_cast<internal::BiggestInt>(fp)));
1109 EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, PrintByRef(fp));
1110 }
1111
1112 // Tests that the universal printer prints a member function pointer
1113 // passed by reference.
TEST(PrintReferenceTest,HandlesMemberFunctionPointer)1114 TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
1115 int (Foo::*p)(char ch) = &Foo::MyMethod;
1116 EXPECT_TRUE(HasPrefix(PrintByRef(p),
1117 "@" + PrintPointer(reinterpret_cast<const void*>(&p)) +
1118 " " + Print(sizeof(p)) + "-byte object "));
1119
1120 char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
1121 EXPECT_TRUE(HasPrefix(PrintByRef(p2),
1122 "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) +
1123 " " + Print(sizeof(p2)) + "-byte object "));
1124 }
1125
1126 // Tests that the universal printer prints a member variable pointer
1127 // passed by reference.
TEST(PrintReferenceTest,HandlesMemberVariablePointer)1128 TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
1129 int Foo::*p = &Foo::value; // NOLINT
1130 EXPECT_TRUE(HasPrefix(PrintByRef(p), "@" + PrintPointer(&p) + " " +
1131 Print(sizeof(p)) + "-byte object "));
1132 }
1133
1134 // Tests that FormatForComparisonFailureMessage(), which is used to print
1135 // an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion
1136 // fails, formats the operand in the desired way.
1137
1138 // scalar
TEST(FormatForComparisonFailureMessageTest,WorksForScalar)1139 TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
1140 EXPECT_STREQ("123", FormatForComparisonFailureMessage(123, 124).c_str());
1141 }
1142
1143 // non-char pointer
TEST(FormatForComparisonFailureMessageTest,WorksForNonCharPointer)1144 TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {
1145 int n = 0;
1146 EXPECT_EQ(PrintPointer(&n),
1147 FormatForComparisonFailureMessage(&n, &n).c_str());
1148 }
1149
1150 // non-char array
TEST(FormatForComparisonFailureMessageTest,FormatsNonCharArrayAsPointer)1151 TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
1152 // In expression 'array == x', 'array' is compared by pointer.
1153 // Therefore we want to print an array operand as a pointer.
1154 int n[] = {1, 2, 3};
1155 EXPECT_EQ(PrintPointer(n), FormatForComparisonFailureMessage(n, n).c_str());
1156 }
1157
1158 // Tests formatting a char pointer when it's compared with another pointer.
1159 // In this case we want to print it as a raw pointer, as the comparison is by
1160 // pointer.
1161
1162 // char pointer vs pointer
TEST(FormatForComparisonFailureMessageTest,WorksForCharPointerVsPointer)1163 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
1164 // In expression 'p == x', where 'p' and 'x' are (const or not) char
1165 // pointers, the operands are compared by pointer. Therefore we
1166 // want to print 'p' as a pointer instead of a C string (we don't
1167 // even know if it's supposed to point to a valid C string).
1168
1169 // const char*
1170 const char* s = "hello";
1171 EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
1172
1173 // char*
1174 char ch = 'a';
1175 EXPECT_EQ(PrintPointer(&ch),
1176 FormatForComparisonFailureMessage(&ch, &ch).c_str());
1177 }
1178
1179 // wchar_t pointer vs pointer
TEST(FormatForComparisonFailureMessageTest,WorksForWCharPointerVsPointer)1180 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
1181 // In expression 'p == x', where 'p' and 'x' are (const or not) char
1182 // pointers, the operands are compared by pointer. Therefore we
1183 // want to print 'p' as a pointer instead of a wide C string (we don't
1184 // even know if it's supposed to point to a valid wide C string).
1185
1186 // const wchar_t*
1187 const wchar_t* s = L"hello";
1188 EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
1189
1190 // wchar_t*
1191 wchar_t ch = L'a';
1192 EXPECT_EQ(PrintPointer(&ch),
1193 FormatForComparisonFailureMessage(&ch, &ch).c_str());
1194 }
1195
1196 // Tests formatting a char pointer when it's compared to a string object.
1197 // In this case we want to print the char pointer as a C string.
1198
1199 // char pointer vs std::string
TEST(FormatForComparisonFailureMessageTest,WorksForCharPointerVsStdString)1200 TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) {
1201 const char* s = "hello \"world";
1202 EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped.
1203 FormatForComparisonFailureMessage(s, ::std::string()).c_str());
1204
1205 // char*
1206 char str[] = "hi\1";
1207 char* p = str;
1208 EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped.
1209 FormatForComparisonFailureMessage(p, ::std::string()).c_str());
1210 }
1211
1212 #if GTEST_HAS_STD_WSTRING
1213 // wchar_t pointer vs std::wstring
TEST(FormatForComparisonFailureMessageTest,WorksForWCharPointerVsStdWString)1214 TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) {
1215 const wchar_t* s = L"hi \"world";
1216 EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped.
1217 FormatForComparisonFailureMessage(s, ::std::wstring()).c_str());
1218
1219 // wchar_t*
1220 wchar_t str[] = L"hi\1";
1221 wchar_t* p = str;
1222 EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped.
1223 FormatForComparisonFailureMessage(p, ::std::wstring()).c_str());
1224 }
1225 #endif
1226
1227 // Tests formatting a char array when it's compared with a pointer or array.
1228 // In this case we want to print the array as a row pointer, as the comparison
1229 // is by pointer.
1230
1231 // char array vs pointer
TEST(FormatForComparisonFailureMessageTest,WorksForCharArrayVsPointer)1232 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) {
1233 char str[] = "hi \"world\"";
1234 char* p = nullptr;
1235 EXPECT_EQ(PrintPointer(str),
1236 FormatForComparisonFailureMessage(str, p).c_str());
1237 }
1238
1239 // char array vs char array
TEST(FormatForComparisonFailureMessageTest,WorksForCharArrayVsCharArray)1240 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) {
1241 const char str[] = "hi \"world\"";
1242 EXPECT_EQ(PrintPointer(str),
1243 FormatForComparisonFailureMessage(str, str).c_str());
1244 }
1245
1246 // wchar_t array vs pointer
TEST(FormatForComparisonFailureMessageTest,WorksForWCharArrayVsPointer)1247 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) {
1248 wchar_t str[] = L"hi \"world\"";
1249 wchar_t* p = nullptr;
1250 EXPECT_EQ(PrintPointer(str),
1251 FormatForComparisonFailureMessage(str, p).c_str());
1252 }
1253
1254 // wchar_t array vs wchar_t array
TEST(FormatForComparisonFailureMessageTest,WorksForWCharArrayVsWCharArray)1255 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) {
1256 const wchar_t str[] = L"hi \"world\"";
1257 EXPECT_EQ(PrintPointer(str),
1258 FormatForComparisonFailureMessage(str, str).c_str());
1259 }
1260
1261 // Tests formatting a char array when it's compared with a string object.
1262 // In this case we want to print the array as a C string.
1263
1264 // char array vs std::string
TEST(FormatForComparisonFailureMessageTest,WorksForCharArrayVsStdString)1265 TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) {
1266 const char str[] = "hi \"world\"";
1267 EXPECT_STREQ("\"hi \\\"world\\\"\"", // The content should be escaped.
1268 FormatForComparisonFailureMessage(str, ::std::string()).c_str());
1269 }
1270
1271 #if GTEST_HAS_STD_WSTRING
1272 // wchar_t array vs std::wstring
TEST(FormatForComparisonFailureMessageTest,WorksForWCharArrayVsStdWString)1273 TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
1274 const wchar_t str[] = L"hi \"w\0rld\"";
1275 EXPECT_STREQ(
1276 "L\"hi \\\"w\"", // The content should be escaped.
1277 // Embedded NUL terminates the string.
1278 FormatForComparisonFailureMessage(str, ::std::wstring()).c_str());
1279 }
1280 #endif
1281
1282 // Useful for testing PrintToString(). We cannot use EXPECT_EQ()
1283 // there as its implementation uses PrintToString(). The caller must
1284 // ensure that 'value' has no side effect.
1285 #define EXPECT_PRINT_TO_STRING_(value, expected_string) \
1286 EXPECT_TRUE(PrintToString(value) == (expected_string)) \
1287 << " where " #value " prints as " << (PrintToString(value))
1288
TEST(PrintToStringTest,WorksForScalar)1289 TEST(PrintToStringTest, WorksForScalar) { EXPECT_PRINT_TO_STRING_(123, "123"); }
1290
TEST(PrintToStringTest,WorksForPointerToConstChar)1291 TEST(PrintToStringTest, WorksForPointerToConstChar) {
1292 const char* p = "hello";
1293 EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1294 }
1295
TEST(PrintToStringTest,WorksForPointerToNonConstChar)1296 TEST(PrintToStringTest, WorksForPointerToNonConstChar) {
1297 char s[] = "hello";
1298 char* p = s;
1299 EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1300 }
1301
TEST(PrintToStringTest,EscapesForPointerToConstChar)1302 TEST(PrintToStringTest, EscapesForPointerToConstChar) {
1303 const char* p = "hello\n";
1304 EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\"");
1305 }
1306
TEST(PrintToStringTest,EscapesForPointerToNonConstChar)1307 TEST(PrintToStringTest, EscapesForPointerToNonConstChar) {
1308 char s[] = "hello\1";
1309 char* p = s;
1310 EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\"");
1311 }
1312
TEST(PrintToStringTest,WorksForArray)1313 TEST(PrintToStringTest, WorksForArray) {
1314 int n[3] = {1, 2, 3};
1315 EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }");
1316 }
1317
TEST(PrintToStringTest,WorksForCharArray)1318 TEST(PrintToStringTest, WorksForCharArray) {
1319 char s[] = "hello";
1320 EXPECT_PRINT_TO_STRING_(s, "\"hello\"");
1321 }
1322
TEST(PrintToStringTest,WorksForCharArrayWithEmbeddedNul)1323 TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {
1324 const char str_with_nul[] = "hello\0 world";
1325 EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\"");
1326
1327 char mutable_str_with_nul[] = "hello\0 world";
1328 EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\"");
1329 }
1330
TEST(PrintToStringTest,ContainsNonLatin)1331 TEST(PrintToStringTest, ContainsNonLatin) {
1332 // Sanity test with valid UTF-8. Prints both in hex and as text.
1333 std::string non_ascii_str = ::std::string("오전 4:30");
1334 EXPECT_PRINT_TO_STRING_(non_ascii_str,
1335 "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n"
1336 " As Text: \"오전 4:30\"");
1337 non_ascii_str = ::std::string("From ä — ẑ");
1338 EXPECT_PRINT_TO_STRING_(non_ascii_str,
1339 "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\""
1340 "\n As Text: \"From ä — ẑ\"");
1341 }
1342
TEST(IsValidUTF8Test,IllFormedUTF8)1343 TEST(IsValidUTF8Test, IllFormedUTF8) {
1344 // The following test strings are ill-formed UTF-8 and are printed
1345 // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is
1346 // expected to fail, thus output does not contain "As Text:".
1347
1348 static const char* const kTestdata[][2] = {
1349 // 2-byte lead byte followed by a single-byte character.
1350 {"\xC3\x74", "\"\\xC3t\""},
1351 // Valid 2-byte character followed by an orphan trail byte.
1352 {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""},
1353 // Lead byte without trail byte.
1354 {"abc\xC3", "\"abc\\xC3\""},
1355 // 3-byte lead byte, single-byte character, orphan trail byte.
1356 {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""},
1357 // Truncated 3-byte character.
1358 {"\xE2\x80", "\"\\xE2\\x80\""},
1359 // Truncated 3-byte character followed by valid 2-byte char.
1360 {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""},
1361 // Truncated 3-byte character followed by a single-byte character.
1362 {"\xE2\x80\x7A", "\"\\xE2\\x80z\""},
1363 // 3-byte lead byte followed by valid 3-byte character.
1364 {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""},
1365 // 4-byte lead byte followed by valid 3-byte character.
1366 {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""},
1367 // Truncated 4-byte character.
1368 {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""},
1369 // Invalid UTF-8 byte sequences embedded in other chars.
1370 {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""},
1371 {"abc\xC3\x84\xE2\x80\xC3\x84xyz",
1372 "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""},
1373 // Non-shortest UTF-8 byte sequences are also ill-formed.
1374 // The classics: xC0, xC1 lead byte.
1375 {"\xC0\x80", "\"\\xC0\\x80\""},
1376 {"\xC1\x81", "\"\\xC1\\x81\""},
1377 // Non-shortest sequences.
1378 {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
1379 {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
1380 // Last valid code point before surrogate range, should be printed as
1381 // text,
1382 // too.
1383 {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"\""},
1384 // Start of surrogate lead. Surrogates are not printed as text.
1385 {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""},
1386 // Last non-private surrogate lead.
1387 {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""},
1388 // First private-use surrogate lead.
1389 {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""},
1390 // Last private-use surrogate lead.
1391 {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
1392 // Mid-point of surrogate trail.
1393 {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
1394 // First valid code point after surrogate range, should be printed as
1395 // text,
1396 // too.
1397 {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""}};
1398
1399 for (int i = 0; i < int(sizeof(kTestdata) / sizeof(kTestdata[0])); ++i) {
1400 EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
1401 }
1402 }
1403
1404 #undef EXPECT_PRINT_TO_STRING_
1405
TEST(UniversalTersePrintTest,WorksForNonReference)1406 TEST(UniversalTersePrintTest, WorksForNonReference) {
1407 ::std::stringstream ss;
1408 UniversalTersePrint(123, &ss);
1409 EXPECT_EQ("123", ss.str());
1410 }
1411
TEST(UniversalTersePrintTest,WorksForReference)1412 TEST(UniversalTersePrintTest, WorksForReference) {
1413 const int& n = 123;
1414 ::std::stringstream ss;
1415 UniversalTersePrint(n, &ss);
1416 EXPECT_EQ("123", ss.str());
1417 }
1418
TEST(UniversalTersePrintTest,WorksForCString)1419 TEST(UniversalTersePrintTest, WorksForCString) {
1420 const char* s1 = "abc";
1421 ::std::stringstream ss1;
1422 UniversalTersePrint(s1, &ss1);
1423 EXPECT_EQ("\"abc\"", ss1.str());
1424
1425 char* s2 = const_cast<char*>(s1);
1426 ::std::stringstream ss2;
1427 UniversalTersePrint(s2, &ss2);
1428 EXPECT_EQ("\"abc\"", ss2.str());
1429
1430 const char* s3 = nullptr;
1431 ::std::stringstream ss3;
1432 UniversalTersePrint(s3, &ss3);
1433 EXPECT_EQ("NULL", ss3.str());
1434 }
1435
TEST(UniversalPrintTest,WorksForNonReference)1436 TEST(UniversalPrintTest, WorksForNonReference) {
1437 ::std::stringstream ss;
1438 UniversalPrint(123, &ss);
1439 EXPECT_EQ("123", ss.str());
1440 }
1441
TEST(UniversalPrintTest,WorksForReference)1442 TEST(UniversalPrintTest, WorksForReference) {
1443 const int& n = 123;
1444 ::std::stringstream ss;
1445 UniversalPrint(n, &ss);
1446 EXPECT_EQ("123", ss.str());
1447 }
1448
TEST(UniversalPrintTest,WorksForCString)1449 TEST(UniversalPrintTest, WorksForCString) {
1450 const char* s1 = "abc";
1451 ::std::stringstream ss1;
1452 UniversalPrint(s1, &ss1);
1453 EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str()));
1454
1455 char* s2 = const_cast<char*>(s1);
1456 ::std::stringstream ss2;
1457 UniversalPrint(s2, &ss2);
1458 EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str()));
1459
1460 const char* s3 = nullptr;
1461 ::std::stringstream ss3;
1462 UniversalPrint(s3, &ss3);
1463 EXPECT_EQ("NULL", ss3.str());
1464 }
1465
TEST(UniversalPrintTest,WorksForCharArray)1466 TEST(UniversalPrintTest, WorksForCharArray) {
1467 const char str[] = "\"Line\0 1\"\nLine 2";
1468 ::std::stringstream ss1;
1469 UniversalPrint(str, &ss1);
1470 EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str());
1471
1472 const char mutable_str[] = "\"Line\0 1\"\nLine 2";
1473 ::std::stringstream ss2;
1474 UniversalPrint(mutable_str, &ss2);
1475 EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str());
1476 }
1477
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd,PrintsEmptyTuple)1478 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
1479 Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
1480 EXPECT_EQ(0u, result.size());
1481 }
1482
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd,PrintsOneTuple)1483 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
1484 Strings result =
1485 UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1));
1486 ASSERT_EQ(1u, result.size());
1487 EXPECT_EQ("1", result[0]);
1488 }
1489
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd,PrintsTwoTuple)1490 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
1491 Strings result =
1492 UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1, 'a'));
1493 ASSERT_EQ(2u, result.size());
1494 EXPECT_EQ("1", result[0]);
1495 EXPECT_EQ("'a' (97, 0x61)", result[1]);
1496 }
1497
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd,PrintsTersely)1498 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
1499 const int n = 1;
1500 Strings result = UniversalTersePrintTupleFieldsToStrings(
1501 ::std::tuple<const int&, const char*>(n, "a"));
1502 ASSERT_EQ(2u, result.size());
1503 EXPECT_EQ("1", result[0]);
1504 EXPECT_EQ("\"a\"", result[1]);
1505 }
1506
1507 #if GTEST_HAS_ABSL
1508
TEST(PrintOptionalTest,Basic)1509 TEST(PrintOptionalTest, Basic) {
1510 absl::optional<int> value;
1511 EXPECT_EQ("(nullopt)", PrintToString(value));
1512 value = {7};
1513 EXPECT_EQ("(7)", PrintToString(value));
1514 EXPECT_EQ("(1.1)", PrintToString(absl::optional<double>{1.1}));
1515 EXPECT_EQ("(\"A\")", PrintToString(absl::optional<std::string>{"A"}));
1516 }
1517
1518 struct NonPrintable {
1519 unsigned char contents = 17;
1520 };
1521
TEST(PrintOneofTest,Basic)1522 TEST(PrintOneofTest, Basic) {
1523 using Type = absl::variant<int, StreamableInGlobal, NonPrintable>;
1524 EXPECT_EQ("('int' with value 7)", PrintToString(Type(7)));
1525 EXPECT_EQ("('StreamableInGlobal' with value StreamableInGlobal)",
1526 PrintToString(Type(StreamableInGlobal{})));
1527 EXPECT_EQ(
1528 "('testing::gtest_printers_test::NonPrintable' with value 1-byte object "
1529 "<11>)",
1530 PrintToString(Type(NonPrintable{})));
1531 }
1532 #endif // GTEST_HAS_ABSL
1533 namespace {
1534 class string_ref;
1535
1536 /**
1537 * This is a synthetic pointer to a fixed size string.
1538 */
1539 class string_ptr {
1540 public:
string_ptr(const char * data,size_t size)1541 string_ptr(const char* data, size_t size) : data_(data), size_(size) {}
1542
operator ++()1543 string_ptr& operator++() noexcept {
1544 data_ += size_;
1545 return *this;
1546 }
1547
1548 string_ref operator*() const noexcept;
1549
1550 private:
1551 const char* data_;
1552 size_t size_;
1553 };
1554
1555 /**
1556 * This is a synthetic reference of a fixed size string.
1557 */
1558 class string_ref {
1559 public:
string_ref(const char * data,size_t size)1560 string_ref(const char* data, size_t size) : data_(data), size_(size) {}
1561
operator &() const1562 string_ptr operator&() const noexcept { return {data_, size_}; } // NOLINT
1563
operator ==(const char * s) const1564 bool operator==(const char* s) const noexcept {
1565 if (size_ > 0 && data_[size_ - 1] != 0) {
1566 return std::string(data_, size_) == std::string(s);
1567 } else {
1568 return std::string(data_) == std::string(s);
1569 }
1570 }
1571
1572 private:
1573 const char* data_;
1574 size_t size_;
1575 };
1576
operator *() const1577 string_ref string_ptr::operator*() const noexcept { return {data_, size_}; }
1578
TEST(string_ref,compare)1579 TEST(string_ref, compare) {
1580 const char* s = "alex\0davidjohn\0";
1581 string_ptr ptr(s, 5);
1582 EXPECT_EQ(*ptr, "alex");
1583 EXPECT_TRUE(*ptr == "alex");
1584 ++ptr;
1585 EXPECT_EQ(*ptr, "david");
1586 EXPECT_TRUE(*ptr == "david");
1587 ++ptr;
1588 EXPECT_EQ(*ptr, "john");
1589 }
1590
1591 } // namespace
1592
1593 } // namespace gtest_printers_test
1594 } // namespace testing
1595