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