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 // Author: wan@google.com (Zhanyong Wan)
31 
32 // Google Test - The Google C++ Testing Framework
33 //
34 // This file tests the universal value printer.
35 
36 #include "gtest/gtest-printers.h"
37 
38 #include <ctype.h>
39 #include <limits.h>
40 #include <string.h>
41 #include <algorithm>
42 #include <deque>
43 #include <list>
44 #include <map>
45 #include <set>
46 #include <sstream>
47 #include <string>
48 #include <utility>
49 #include <vector>
50 
51 #include "gtest/gtest.h"
52 
53 // hash_map and hash_set are available under Visual C++.
54 #if _MSC_VER
55 # define GTEST_HAS_HASH_MAP_ 1  // Indicates that hash_map is available.
56 # include <hash_map>            // NOLINT
57 # define GTEST_HAS_HASH_SET_ 1  // Indicates that hash_set is available.
58 # include <hash_set>            // NOLINT
59 #endif  // GTEST_OS_WINDOWS
60 
61 // Some user-defined types for testing the universal value printer.
62 
63 // An anonymous enum type.
64 enum AnonymousEnum {
65   kAE1 = -1,
66   kAE2 = 1
67 };
68 
69 // An enum without a user-defined printer.
70 enum EnumWithoutPrinter {
71   kEWP1 = -2,
72   kEWP2 = 42
73 };
74 
75 // An enum with a << operator.
76 enum EnumWithStreaming {
77   kEWS1 = 10
78 };
79 
operator <<(std::ostream & os,EnumWithStreaming e)80 std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
81   return os << (e == kEWS1 ? "kEWS1" : "invalid");
82 }
83 
84 // An enum with a PrintTo() function.
85 enum EnumWithPrintTo {
86   kEWPT1 = 1
87 };
88 
PrintTo(EnumWithPrintTo e,std::ostream * os)89 void PrintTo(EnumWithPrintTo e, std::ostream* os) {
90   *os << (e == kEWPT1 ? "kEWPT1" : "invalid");
91 }
92 
93 // A class implicitly convertible to BiggestInt.
94 class BiggestIntConvertible {
95  public:
operator ::testing::internal::BiggestInt() const96   operator ::testing::internal::BiggestInt() const { return 42; }
97 };
98 
99 // A user-defined unprintable class template in the global namespace.
100 template <typename T>
101 class UnprintableTemplateInGlobal {
102  public:
UnprintableTemplateInGlobal()103   UnprintableTemplateInGlobal() : value_() {}
104  private:
105   T value_;
106 };
107 
108 // A user-defined streamable type in the global namespace.
109 class StreamableInGlobal {
110  public:
~StreamableInGlobal()111   virtual ~StreamableInGlobal() {}
112 };
113 
operator <<(::std::ostream & os,const StreamableInGlobal &)114 inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) {
115   os << "StreamableInGlobal";
116 }
117 
operator <<(::std::ostream & os,const StreamableInGlobal *)118 void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) {
119   os << "StreamableInGlobal*";
120 }
121 
122 namespace foo {
123 
124 // A user-defined unprintable type in a user namespace.
125 class UnprintableInFoo {
126  public:
UnprintableInFoo()127   UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
128  private:
129   char xy_[8];
130   double z_;
131 };
132 
133 // A user-defined printable type in a user-chosen namespace.
134 struct PrintableViaPrintTo {
PrintableViaPrintTofoo::PrintableViaPrintTo135   PrintableViaPrintTo() : value() {}
136   int value;
137 };
138 
PrintTo(const PrintableViaPrintTo & x,::std::ostream * os)139 void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
140   *os << "PrintableViaPrintTo: " << x.value;
141 }
142 
143 // A type with a user-defined << for printing its pointer.
144 struct PointerPrintable {
145 };
146 
operator <<(::std::ostream & os,const PointerPrintable *)147 ::std::ostream& operator<<(::std::ostream& os,
148                            const PointerPrintable* /* x */) {
149   return os << "PointerPrintable*";
150 }
151 
152 // A user-defined printable class template in a user-chosen namespace.
153 template <typename T>
154 class PrintableViaPrintToTemplate {
155  public:
PrintableViaPrintToTemplate(const T & a_value)156   explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
157 
value() const158   const T& value() const { return value_; }
159  private:
160   T value_;
161 };
162 
163 template <typename T>
PrintTo(const PrintableViaPrintToTemplate<T> & x,::std::ostream * os)164 void PrintTo(const PrintableViaPrintToTemplate<T>& x, ::std::ostream* os) {
165   *os << "PrintableViaPrintToTemplate: " << x.value();
166 }
167 
168 // A user-defined streamable class template in a user namespace.
169 template <typename T>
170 class StreamableTemplateInFoo {
171  public:
StreamableTemplateInFoo()172   StreamableTemplateInFoo() : value_() {}
173 
value() const174   const T& value() const { return value_; }
175  private:
176   T value_;
177 };
178 
179 template <typename T>
operator <<(::std::ostream & os,const StreamableTemplateInFoo<T> & x)180 inline ::std::ostream& operator<<(::std::ostream& os,
181                                   const StreamableTemplateInFoo<T>& x) {
182   return os << "StreamableTemplateInFoo: " << x.value();
183 }
184 
185 }  // namespace foo
186 
187 namespace testing {
188 namespace gtest_printers_test {
189 
190 using ::std::deque;
191 using ::std::list;
192 using ::std::make_pair;
193 using ::std::map;
194 using ::std::multimap;
195 using ::std::multiset;
196 using ::std::pair;
197 using ::std::set;
198 using ::std::vector;
199 using ::testing::PrintToString;
200 using ::testing::internal::ImplicitCast_;
201 using ::testing::internal::NativeArray;
202 using ::testing::internal::RE;
203 using ::testing::internal::Strings;
204 using ::testing::internal::UniversalTersePrint;
205 using ::testing::internal::UniversalPrint;
206 using ::testing::internal::UniversalTersePrintTupleFieldsToStrings;
207 using ::testing::internal::UniversalPrinter;
208 using ::testing::internal::kReference;
209 using ::testing::internal::string;
210 
211 #if GTEST_HAS_TR1_TUPLE
212 using ::std::tr1::make_tuple;
213 using ::std::tr1::tuple;
214 #endif
215 
216 #if _MSC_VER
217 // MSVC defines the following classes in the ::stdext namespace while
218 // gcc defines them in the :: namespace.  Note that they are not part
219 // of the C++ standard.
220 using ::stdext::hash_map;
221 using ::stdext::hash_set;
222 using ::stdext::hash_multimap;
223 using ::stdext::hash_multiset;
224 #endif
225 
226 // Prints a value to a string using the universal value printer.  This
227 // is a helper for testing UniversalPrinter<T>::Print() for various types.
228 template <typename T>
Print(const T & value)229 string Print(const T& value) {
230   ::std::stringstream ss;
231   UniversalPrinter<T>::Print(value, &ss);
232   return ss.str();
233 }
234 
235 // Prints a value passed by reference to a string, using the universal
236 // value printer.  This is a helper for testing
237 // UniversalPrinter<T&>::Print() for various types.
238 template <typename T>
PrintByRef(const T & value)239 string PrintByRef(const T& value) {
240   ::std::stringstream ss;
241   UniversalPrinter<T&>::Print(value, &ss);
242   return ss.str();
243 }
244 
245 // Tests printing various enum types.
246 
TEST(PrintEnumTest,AnonymousEnum)247 TEST(PrintEnumTest, AnonymousEnum) {
248   EXPECT_EQ("-1", Print(kAE1));
249   EXPECT_EQ("1", Print(kAE2));
250 }
251 
TEST(PrintEnumTest,EnumWithoutPrinter)252 TEST(PrintEnumTest, EnumWithoutPrinter) {
253   EXPECT_EQ("-2", Print(kEWP1));
254   EXPECT_EQ("42", Print(kEWP2));
255 }
256 
TEST(PrintEnumTest,EnumWithStreaming)257 TEST(PrintEnumTest, EnumWithStreaming) {
258   EXPECT_EQ("kEWS1", Print(kEWS1));
259   EXPECT_EQ("invalid", Print(static_cast<EnumWithStreaming>(0)));
260 }
261 
TEST(PrintEnumTest,EnumWithPrintTo)262 TEST(PrintEnumTest, EnumWithPrintTo) {
263   EXPECT_EQ("kEWPT1", Print(kEWPT1));
264   EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0)));
265 }
266 
267 // Tests printing a class implicitly convertible to BiggestInt.
268 
TEST(PrintClassTest,BiggestIntConvertible)269 TEST(PrintClassTest, BiggestIntConvertible) {
270   EXPECT_EQ("42", Print(BiggestIntConvertible()));
271 }
272 
273 // Tests printing various char types.
274 
275 // char.
TEST(PrintCharTest,PlainChar)276 TEST(PrintCharTest, PlainChar) {
277   EXPECT_EQ("'\\0'", Print('\0'));
278   EXPECT_EQ("'\\'' (39, 0x27)", Print('\''));
279   EXPECT_EQ("'\"' (34, 0x22)", Print('"'));
280   EXPECT_EQ("'?' (63, 0x3F)", Print('?'));
281   EXPECT_EQ("'\\\\' (92, 0x5C)", Print('\\'));
282   EXPECT_EQ("'\\a' (7)", Print('\a'));
283   EXPECT_EQ("'\\b' (8)", Print('\b'));
284   EXPECT_EQ("'\\f' (12, 0xC)", Print('\f'));
285   EXPECT_EQ("'\\n' (10, 0xA)", Print('\n'));
286   EXPECT_EQ("'\\r' (13, 0xD)", Print('\r'));
287   EXPECT_EQ("'\\t' (9)", Print('\t'));
288   EXPECT_EQ("'\\v' (11, 0xB)", Print('\v'));
289   EXPECT_EQ("'\\x7F' (127)", Print('\x7F'));
290   EXPECT_EQ("'\\xFF' (255)", Print('\xFF'));
291   EXPECT_EQ("' ' (32, 0x20)", Print(' '));
292   EXPECT_EQ("'a' (97, 0x61)", Print('a'));
293 }
294 
295 // signed char.
TEST(PrintCharTest,SignedChar)296 TEST(PrintCharTest, SignedChar) {
297   EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0')));
298   EXPECT_EQ("'\\xCE' (-50)",
299             Print(static_cast<signed char>(-50)));
300 }
301 
302 // unsigned char.
TEST(PrintCharTest,UnsignedChar)303 TEST(PrintCharTest, UnsignedChar) {
304   EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0')));
305   EXPECT_EQ("'b' (98, 0x62)",
306             Print(static_cast<unsigned char>('b')));
307 }
308 
309 // Tests printing other simple, built-in types.
310 
311 // bool.
TEST(PrintBuiltInTypeTest,Bool)312 TEST(PrintBuiltInTypeTest, Bool) {
313   EXPECT_EQ("false", Print(false));
314   EXPECT_EQ("true", Print(true));
315 }
316 
317 // wchar_t.
TEST(PrintBuiltInTypeTest,Wchar_t)318 TEST(PrintBuiltInTypeTest, Wchar_t) {
319   EXPECT_EQ("L'\\0'", Print(L'\0'));
320   EXPECT_EQ("L'\\'' (39, 0x27)", Print(L'\''));
321   EXPECT_EQ("L'\"' (34, 0x22)", Print(L'"'));
322   EXPECT_EQ("L'?' (63, 0x3F)", Print(L'?'));
323   EXPECT_EQ("L'\\\\' (92, 0x5C)", Print(L'\\'));
324   EXPECT_EQ("L'\\a' (7)", Print(L'\a'));
325   EXPECT_EQ("L'\\b' (8)", Print(L'\b'));
326   EXPECT_EQ("L'\\f' (12, 0xC)", Print(L'\f'));
327   EXPECT_EQ("L'\\n' (10, 0xA)", Print(L'\n'));
328   EXPECT_EQ("L'\\r' (13, 0xD)", Print(L'\r'));
329   EXPECT_EQ("L'\\t' (9)", Print(L'\t'));
330   EXPECT_EQ("L'\\v' (11, 0xB)", Print(L'\v'));
331   EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F'));
332   EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF'));
333   EXPECT_EQ("L' ' (32, 0x20)", Print(L' '));
334   EXPECT_EQ("L'a' (97, 0x61)", Print(L'a'));
335   EXPECT_EQ("L'\\x576' (1398)", Print(static_cast<wchar_t>(0x576)));
336   EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast<wchar_t>(0xC74D)));
337 }
338 
339 // Test that Int64 provides more storage than wchar_t.
TEST(PrintTypeSizeTest,Wchar_t)340 TEST(PrintTypeSizeTest, Wchar_t) {
341   EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64));
342 }
343 
344 // Various integer types.
TEST(PrintBuiltInTypeTest,Integer)345 TEST(PrintBuiltInTypeTest, Integer) {
346   EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255)));  // uint8
347   EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128)));  // int8
348   EXPECT_EQ("65535", Print(USHRT_MAX));  // uint16
349   EXPECT_EQ("-32768", Print(SHRT_MIN));  // int16
350   EXPECT_EQ("4294967295", Print(UINT_MAX));  // uint32
351   EXPECT_EQ("-2147483648", Print(INT_MIN));  // int32
352   EXPECT_EQ("18446744073709551615",
353             Print(static_cast<testing::internal::UInt64>(-1)));  // uint64
354   EXPECT_EQ("-9223372036854775808",
355             Print(static_cast<testing::internal::Int64>(1) << 63));  // int64
356 }
357 
358 // Size types.
TEST(PrintBuiltInTypeTest,Size_t)359 TEST(PrintBuiltInTypeTest, Size_t) {
360   EXPECT_EQ("1", Print(sizeof('a')));  // size_t.
361 #if !GTEST_OS_WINDOWS
362   // Windows has no ssize_t type.
363   EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2)));  // ssize_t.
364 #endif  // !GTEST_OS_WINDOWS
365 }
366 
367 // Floating-points.
TEST(PrintBuiltInTypeTest,FloatingPoints)368 TEST(PrintBuiltInTypeTest, FloatingPoints) {
369   EXPECT_EQ("1.5", Print(1.5f));   // float
370   EXPECT_EQ("-2.5", Print(-2.5));  // double
371 }
372 
373 // Since ::std::stringstream::operator<<(const void *) formats the pointer
374 // output differently with different compilers, we have to create the expected
375 // output first and use it as our expectation.
PrintPointer(const void * p)376 static string PrintPointer(const void *p) {
377   ::std::stringstream expected_result_stream;
378   expected_result_stream << p;
379   return expected_result_stream.str();
380 }
381 
382 // Tests printing C strings.
383 
384 // const char*.
TEST(PrintCStringTest,Const)385 TEST(PrintCStringTest, Const) {
386   const char* p = "World";
387   EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p));
388 }
389 
390 // char*.
TEST(PrintCStringTest,NonConst)391 TEST(PrintCStringTest, NonConst) {
392   char p[] = "Hi";
393   EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"",
394             Print(static_cast<char*>(p)));
395 }
396 
397 // NULL C string.
TEST(PrintCStringTest,Null)398 TEST(PrintCStringTest, Null) {
399   const char* p = NULL;
400   EXPECT_EQ("NULL", Print(p));
401 }
402 
403 // Tests that C strings are escaped properly.
TEST(PrintCStringTest,EscapesProperly)404 TEST(PrintCStringTest, EscapesProperly) {
405   const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
406   EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f"
407             "\\n\\r\\t\\v\\x7F\\xFF a\"",
408             Print(p));
409 }
410 
411 
412 
413 // MSVC compiler can be configured to define whar_t as a typedef
414 // of unsigned short. Defining an overload for const wchar_t* in that case
415 // would cause pointers to unsigned shorts be printed as wide strings,
416 // possibly accessing more memory than intended and causing invalid
417 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
418 // wchar_t is implemented as a native type.
419 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
420 
421 // const wchar_t*.
TEST(PrintWideCStringTest,Const)422 TEST(PrintWideCStringTest, Const) {
423   const wchar_t* p = L"World";
424   EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p));
425 }
426 
427 // wchar_t*.
TEST(PrintWideCStringTest,NonConst)428 TEST(PrintWideCStringTest, NonConst) {
429   wchar_t p[] = L"Hi";
430   EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"",
431             Print(static_cast<wchar_t*>(p)));
432 }
433 
434 // NULL wide C string.
TEST(PrintWideCStringTest,Null)435 TEST(PrintWideCStringTest, Null) {
436   const wchar_t* p = NULL;
437   EXPECT_EQ("NULL", Print(p));
438 }
439 
440 // Tests that wide C strings are escaped properly.
TEST(PrintWideCStringTest,EscapesProperly)441 TEST(PrintWideCStringTest, EscapesProperly) {
442   const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r',
443                        '\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'};
444   EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f"
445             "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
446             Print(static_cast<const wchar_t*>(s)));
447 }
448 #endif  // native wchar_t
449 
450 // Tests printing pointers to other char types.
451 
452 // signed char*.
TEST(PrintCharPointerTest,SignedChar)453 TEST(PrintCharPointerTest, SignedChar) {
454   signed char* p = reinterpret_cast<signed char*>(0x1234);
455   EXPECT_EQ(PrintPointer(p), Print(p));
456   p = NULL;
457   EXPECT_EQ("NULL", Print(p));
458 }
459 
460 // const signed char*.
TEST(PrintCharPointerTest,ConstSignedChar)461 TEST(PrintCharPointerTest, ConstSignedChar) {
462   signed char* p = reinterpret_cast<signed char*>(0x1234);
463   EXPECT_EQ(PrintPointer(p), Print(p));
464   p = NULL;
465   EXPECT_EQ("NULL", Print(p));
466 }
467 
468 // unsigned char*.
TEST(PrintCharPointerTest,UnsignedChar)469 TEST(PrintCharPointerTest, UnsignedChar) {
470   unsigned char* p = reinterpret_cast<unsigned char*>(0x1234);
471   EXPECT_EQ(PrintPointer(p), Print(p));
472   p = NULL;
473   EXPECT_EQ("NULL", Print(p));
474 }
475 
476 // const unsigned char*.
TEST(PrintCharPointerTest,ConstUnsignedChar)477 TEST(PrintCharPointerTest, ConstUnsignedChar) {
478   const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234);
479   EXPECT_EQ(PrintPointer(p), Print(p));
480   p = NULL;
481   EXPECT_EQ("NULL", Print(p));
482 }
483 
484 // Tests printing pointers to simple, built-in types.
485 
486 // bool*.
TEST(PrintPointerToBuiltInTypeTest,Bool)487 TEST(PrintPointerToBuiltInTypeTest, Bool) {
488   bool* p = reinterpret_cast<bool*>(0xABCD);
489   EXPECT_EQ(PrintPointer(p), Print(p));
490   p = NULL;
491   EXPECT_EQ("NULL", Print(p));
492 }
493 
494 // void*.
TEST(PrintPointerToBuiltInTypeTest,Void)495 TEST(PrintPointerToBuiltInTypeTest, Void) {
496   void* p = reinterpret_cast<void*>(0xABCD);
497   EXPECT_EQ(PrintPointer(p), Print(p));
498   p = NULL;
499   EXPECT_EQ("NULL", Print(p));
500 }
501 
502 // const void*.
TEST(PrintPointerToBuiltInTypeTest,ConstVoid)503 TEST(PrintPointerToBuiltInTypeTest, ConstVoid) {
504   const void* p = reinterpret_cast<const void*>(0xABCD);
505   EXPECT_EQ(PrintPointer(p), Print(p));
506   p = NULL;
507   EXPECT_EQ("NULL", Print(p));
508 }
509 
510 // Tests printing pointers to pointers.
TEST(PrintPointerToPointerTest,IntPointerPointer)511 TEST(PrintPointerToPointerTest, IntPointerPointer) {
512   int** p = reinterpret_cast<int**>(0xABCD);
513   EXPECT_EQ(PrintPointer(p), Print(p));
514   p = NULL;
515   EXPECT_EQ("NULL", Print(p));
516 }
517 
518 // Tests printing (non-member) function pointers.
519 
MyFunction(int)520 void MyFunction(int /* n */) {}
521 
TEST(PrintPointerTest,NonMemberFunctionPointer)522 TEST(PrintPointerTest, NonMemberFunctionPointer) {
523   // We cannot directly cast &MyFunction to const void* because the
524   // standard disallows casting between pointers to functions and
525   // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
526   // this limitation.
527   EXPECT_EQ(
528       PrintPointer(reinterpret_cast<const void*>(
529           reinterpret_cast<internal::BiggestInt>(&MyFunction))),
530       Print(&MyFunction));
531   int (*p)(bool) = NULL;  // NOLINT
532   EXPECT_EQ("NULL", Print(p));
533 }
534 
535 // An assertion predicate determining whether a one string is a prefix for
536 // another.
537 template <typename StringType>
HasPrefix(const StringType & str,const StringType & prefix)538 AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
539   if (str.find(prefix, 0) == 0)
540     return AssertionSuccess();
541 
542   const bool is_wide_string = sizeof(prefix[0]) > 1;
543   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
544   return AssertionFailure()
545       << begin_string_quote << prefix << "\" is not a prefix of "
546       << begin_string_quote << str << "\"\n";
547 }
548 
549 // Tests printing member variable pointers.  Although they are called
550 // pointers, they don't point to a location in the address space.
551 // Their representation is implementation-defined.  Thus they will be
552 // printed as raw bytes.
553 
554 struct Foo {
555  public:
~Footesting::gtest_printers_test::Foo556   virtual ~Foo() {}
MyMethodtesting::gtest_printers_test::Foo557   int MyMethod(char x) { return x + 1; }
MyVirtualMethodtesting::gtest_printers_test::Foo558   virtual char MyVirtualMethod(int /* n */) { return 'a'; }
559 
560   int value;
561 };
562 
TEST(PrintPointerTest,MemberVariablePointer)563 TEST(PrintPointerTest, MemberVariablePointer) {
564   EXPECT_TRUE(HasPrefix(Print(&Foo::value),
565                         Print(sizeof(&Foo::value)) + "-byte object "));
566   int (Foo::*p) = NULL;  // NOLINT
567   EXPECT_TRUE(HasPrefix(Print(p),
568                         Print(sizeof(p)) + "-byte object "));
569 }
570 
571 // Tests printing member function pointers.  Although they are called
572 // pointers, they don't point to a location in the address space.
573 // Their representation is implementation-defined.  Thus they will be
574 // printed as raw bytes.
TEST(PrintPointerTest,MemberFunctionPointer)575 TEST(PrintPointerTest, MemberFunctionPointer) {
576   EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod),
577                         Print(sizeof(&Foo::MyMethod)) + "-byte object "));
578   EXPECT_TRUE(
579       HasPrefix(Print(&Foo::MyVirtualMethod),
580                 Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
581   int (Foo::*p)(char) = NULL;  // NOLINT
582   EXPECT_TRUE(HasPrefix(Print(p),
583                         Print(sizeof(p)) + "-byte object "));
584 }
585 
586 // Tests printing C arrays.
587 
588 // The difference between this and Print() is that it ensures that the
589 // argument is a reference to an array.
590 template <typename T, size_t N>
PrintArrayHelper(T (& a)[N])591 string PrintArrayHelper(T (&a)[N]) {
592   return Print(a);
593 }
594 
595 // One-dimensional array.
TEST(PrintArrayTest,OneDimensionalArray)596 TEST(PrintArrayTest, OneDimensionalArray) {
597   int a[5] = { 1, 2, 3, 4, 5 };
598   EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
599 }
600 
601 // Two-dimensional array.
TEST(PrintArrayTest,TwoDimensionalArray)602 TEST(PrintArrayTest, TwoDimensionalArray) {
603   int a[2][5] = {
604     { 1, 2, 3, 4, 5 },
605     { 6, 7, 8, 9, 0 }
606   };
607   EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
608 }
609 
610 // Array of const elements.
TEST(PrintArrayTest,ConstArray)611 TEST(PrintArrayTest, ConstArray) {
612   const bool a[1] = { false };
613   EXPECT_EQ("{ false }", PrintArrayHelper(a));
614 }
615 
616 // Char array.
TEST(PrintArrayTest,CharArray)617 TEST(PrintArrayTest, CharArray) {
618   // Array a contains '\0' in the middle and doesn't end with '\0'.
619   char a[3] = { 'H', '\0', 'i' };
620   EXPECT_EQ("\"H\\0i\"", PrintArrayHelper(a));
621 }
622 
623 // Const char array.
TEST(PrintArrayTest,ConstCharArray)624 TEST(PrintArrayTest, ConstCharArray) {
625   const char a[4] = "\0Hi";
626   EXPECT_EQ("\"\\0Hi\\0\"", PrintArrayHelper(a));
627 }
628 
629 // Array of objects.
TEST(PrintArrayTest,ObjectArray)630 TEST(PrintArrayTest, ObjectArray) {
631   string a[3] = { "Hi", "Hello", "Ni hao" };
632   EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a));
633 }
634 
635 // Array with many elements.
TEST(PrintArrayTest,BigArray)636 TEST(PrintArrayTest, BigArray) {
637   int a[100] = { 1, 2, 3 };
638   EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }",
639             PrintArrayHelper(a));
640 }
641 
642 // Tests printing ::string and ::std::string.
643 
644 #if GTEST_HAS_GLOBAL_STRING
645 // ::string.
TEST(PrintStringTest,StringInGlobalNamespace)646 TEST(PrintStringTest, StringInGlobalNamespace) {
647   const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
648   const ::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 #endif  // GTEST_HAS_GLOBAL_STRING
653 
654 // ::std::string.
TEST(PrintStringTest,StringInStdNamespace)655 TEST(PrintStringTest, StringInStdNamespace) {
656   const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
657   const ::std::string str(s, sizeof(s));
658   EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
659             Print(str));
660 }
661 
TEST(PrintStringTest,StringAmbiguousHex)662 TEST(PrintStringTest, StringAmbiguousHex) {
663   // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of:
664   // '\x6', '\x6B', or '\x6BA'.
665 
666   // a hex escaping sequence following by a decimal digit
667   EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3")));
668   // a hex escaping sequence following by a hex digit (lower-case)
669   EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas")));
670   // a hex escaping sequence following by a hex digit (upper-case)
671   EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA")));
672   // a hex escaping sequence following by a non-xdigit
673   EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
674 }
675 
676 // Tests printing ::wstring and ::std::wstring.
677 
678 #if GTEST_HAS_GLOBAL_WSTRING
679 // ::wstring.
TEST(PrintWideStringTest,StringInGlobalNamespace)680 TEST(PrintWideStringTest, StringInGlobalNamespace) {
681   const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
682   const ::wstring str(s, sizeof(s)/sizeof(wchar_t));
683   EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
684             "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
685             Print(str));
686 }
687 #endif  // GTEST_HAS_GLOBAL_WSTRING
688 
689 #if GTEST_HAS_STD_WSTRING
690 // ::std::wstring.
TEST(PrintWideStringTest,StringInStdNamespace)691 TEST(PrintWideStringTest, StringInStdNamespace) {
692   const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
693   const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t));
694   EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
695             "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
696             Print(str));
697 }
698 
TEST(PrintWideStringTest,StringAmbiguousHex)699 TEST(PrintWideStringTest, StringAmbiguousHex) {
700   // same for wide strings.
701   EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3")));
702   EXPECT_EQ("L\"mm\\x6\" L\"bananas\"",
703             Print(::std::wstring(L"mm\x6" L"bananas")));
704   EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"",
705             Print(::std::wstring(L"NOM\x6" L"BANANA")));
706   EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
707 }
708 #endif  // GTEST_HAS_STD_WSTRING
709 
710 // Tests printing types that support generic streaming (i.e. streaming
711 // to std::basic_ostream<Char, CharTraits> for any valid Char and
712 // CharTraits types).
713 
714 // Tests printing a non-template type that supports generic streaming.
715 
716 class AllowsGenericStreaming {};
717 
718 template <typename Char, typename CharTraits>
operator <<(std::basic_ostream<Char,CharTraits> & os,const AllowsGenericStreaming &)719 std::basic_ostream<Char, CharTraits>& operator<<(
720     std::basic_ostream<Char, CharTraits>& os,
721     const AllowsGenericStreaming& /* a */) {
722   return os << "AllowsGenericStreaming";
723 }
724 
TEST(PrintTypeWithGenericStreamingTest,NonTemplateType)725 TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) {
726   AllowsGenericStreaming a;
727   EXPECT_EQ("AllowsGenericStreaming", Print(a));
728 }
729 
730 // Tests printing a template type that supports generic streaming.
731 
732 template <typename T>
733 class AllowsGenericStreamingTemplate {};
734 
735 template <typename Char, typename CharTraits, typename T>
operator <<(std::basic_ostream<Char,CharTraits> & os,const AllowsGenericStreamingTemplate<T> &)736 std::basic_ostream<Char, CharTraits>& operator<<(
737     std::basic_ostream<Char, CharTraits>& os,
738     const AllowsGenericStreamingTemplate<T>& /* a */) {
739   return os << "AllowsGenericStreamingTemplate";
740 }
741 
TEST(PrintTypeWithGenericStreamingTest,TemplateType)742 TEST(PrintTypeWithGenericStreamingTest, TemplateType) {
743   AllowsGenericStreamingTemplate<int> a;
744   EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a));
745 }
746 
747 // Tests printing a type that supports generic streaming and can be
748 // implicitly converted to another printable type.
749 
750 template <typename T>
751 class AllowsGenericStreamingAndImplicitConversionTemplate {
752  public:
operator bool() const753   operator bool() const { return false; }
754 };
755 
756 template <typename Char, typename CharTraits, typename T>
operator <<(std::basic_ostream<Char,CharTraits> & os,const AllowsGenericStreamingAndImplicitConversionTemplate<T> &)757 std::basic_ostream<Char, CharTraits>& operator<<(
758     std::basic_ostream<Char, CharTraits>& os,
759     const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) {
760   return os << "AllowsGenericStreamingAndImplicitConversionTemplate";
761 }
762 
TEST(PrintTypeWithGenericStreamingTest,TypeImplicitlyConvertible)763 TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
764   AllowsGenericStreamingAndImplicitConversionTemplate<int> a;
765   EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
766 }
767 
768 #if GTEST_HAS_STRING_PIECE_
769 
770 // Tests printing StringPiece.
771 
TEST(PrintStringPieceTest,SimpleStringPiece)772 TEST(PrintStringPieceTest, SimpleStringPiece) {
773   const StringPiece sp = "Hello";
774   EXPECT_EQ("\"Hello\"", Print(sp));
775 }
776 
TEST(PrintStringPieceTest,UnprintableCharacters)777 TEST(PrintStringPieceTest, UnprintableCharacters) {
778   const char str[] = "NUL (\0) and \r\t";
779   const StringPiece sp(str, sizeof(str) - 1);
780   EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
781 }
782 
783 #endif  // GTEST_HAS_STRING_PIECE_
784 
785 // Tests printing STL containers.
786 
TEST(PrintStlContainerTest,EmptyDeque)787 TEST(PrintStlContainerTest, EmptyDeque) {
788   deque<char> empty;
789   EXPECT_EQ("{}", Print(empty));
790 }
791 
TEST(PrintStlContainerTest,NonEmptyDeque)792 TEST(PrintStlContainerTest, NonEmptyDeque) {
793   deque<int> non_empty;
794   non_empty.push_back(1);
795   non_empty.push_back(3);
796   EXPECT_EQ("{ 1, 3 }", Print(non_empty));
797 }
798 
799 #if GTEST_HAS_HASH_MAP_
800 
TEST(PrintStlContainerTest,OneElementHashMap)801 TEST(PrintStlContainerTest, OneElementHashMap) {
802   hash_map<int, char> map1;
803   map1[1] = 'a';
804   EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1));
805 }
806 
TEST(PrintStlContainerTest,HashMultiMap)807 TEST(PrintStlContainerTest, HashMultiMap) {
808   hash_multimap<int, bool> map1;
809   map1.insert(make_pair(5, true));
810   map1.insert(make_pair(5, false));
811 
812   // Elements of hash_multimap can be printed in any order.
813   const string result = Print(map1);
814   EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
815               result == "{ (5, false), (5, true) }")
816                   << " where Print(map1) returns \"" << result << "\".";
817 }
818 
819 #endif  // GTEST_HAS_HASH_MAP_
820 
821 #if GTEST_HAS_HASH_SET_
822 
TEST(PrintStlContainerTest,HashSet)823 TEST(PrintStlContainerTest, HashSet) {
824   hash_set<string> set1;
825   set1.insert("hello");
826   EXPECT_EQ("{ \"hello\" }", Print(set1));
827 }
828 
TEST(PrintStlContainerTest,HashMultiSet)829 TEST(PrintStlContainerTest, HashMultiSet) {
830   const int kSize = 5;
831   int a[kSize] = { 1, 1, 2, 5, 1 };
832   hash_multiset<int> set1(a, a + kSize);
833 
834   // Elements of hash_multiset can be printed in any order.
835   const string result = Print(set1);
836   const string expected_pattern = "{ d, d, d, d, d }";  // d means a digit.
837 
838   // Verifies the result matches the expected pattern; also extracts
839   // the numbers in the result.
840   ASSERT_EQ(expected_pattern.length(), result.length());
841   std::vector<int> numbers;
842   for (size_t i = 0; i != result.length(); i++) {
843     if (expected_pattern[i] == 'd') {
844       ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
845       numbers.push_back(result[i] - '0');
846     } else {
847       EXPECT_EQ(expected_pattern[i], result[i]) << " where result is "
848                                                 << result;
849     }
850   }
851 
852   // Makes sure the result contains the right numbers.
853   std::sort(numbers.begin(), numbers.end());
854   std::sort(a, a + kSize);
855   EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
856 }
857 
858 #endif  // GTEST_HAS_HASH_SET_
859 
TEST(PrintStlContainerTest,List)860 TEST(PrintStlContainerTest, List) {
861   const string a[] = {
862     "hello",
863     "world"
864   };
865   const list<string> strings(a, a + 2);
866   EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings));
867 }
868 
TEST(PrintStlContainerTest,Map)869 TEST(PrintStlContainerTest, Map) {
870   map<int, bool> map1;
871   map1[1] = true;
872   map1[5] = false;
873   map1[3] = true;
874   EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1));
875 }
876 
TEST(PrintStlContainerTest,MultiMap)877 TEST(PrintStlContainerTest, MultiMap) {
878   multimap<bool, int> map1;
879   // The make_pair template function would deduce the type as
880   // pair<bool, int> here, and since the key part in a multimap has to
881   // be constant, without a templated ctor in the pair class (as in
882   // libCstd on Solaris), make_pair call would fail to compile as no
883   // implicit conversion is found.  Thus explicit typename is used
884   // here instead.
885   map1.insert(pair<const bool, int>(true, 0));
886   map1.insert(pair<const bool, int>(true, 1));
887   map1.insert(pair<const bool, int>(false, 2));
888   EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1));
889 }
890 
TEST(PrintStlContainerTest,Set)891 TEST(PrintStlContainerTest, Set) {
892   const unsigned int a[] = { 3, 0, 5 };
893   set<unsigned int> set1(a, a + 3);
894   EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
895 }
896 
TEST(PrintStlContainerTest,MultiSet)897 TEST(PrintStlContainerTest, MultiSet) {
898   const int a[] = { 1, 1, 2, 5, 1 };
899   multiset<int> set1(a, a + 5);
900   EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
901 }
902 
TEST(PrintStlContainerTest,Pair)903 TEST(PrintStlContainerTest, Pair) {
904   pair<const bool, int> p(true, 5);
905   EXPECT_EQ("(true, 5)", Print(p));
906 }
907 
TEST(PrintStlContainerTest,Vector)908 TEST(PrintStlContainerTest, Vector) {
909   vector<int> v;
910   v.push_back(1);
911   v.push_back(2);
912   EXPECT_EQ("{ 1, 2 }", Print(v));
913 }
914 
TEST(PrintStlContainerTest,LongSequence)915 TEST(PrintStlContainerTest, LongSequence) {
916   const int a[100] = { 1, 2, 3 };
917   const vector<int> v(a, a + 100);
918   EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
919             "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v));
920 }
921 
TEST(PrintStlContainerTest,NestedContainer)922 TEST(PrintStlContainerTest, NestedContainer) {
923   const int a1[] = { 1, 2 };
924   const int a2[] = { 3, 4, 5 };
925   const list<int> l1(a1, a1 + 2);
926   const list<int> l2(a2, a2 + 3);
927 
928   vector<list<int> > v;
929   v.push_back(l1);
930   v.push_back(l2);
931   EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
932 }
933 
TEST(PrintStlContainerTest,OneDimensionalNativeArray)934 TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
935   const int a[3] = { 1, 2, 3 };
936   NativeArray<int> b(a, 3, kReference);
937   EXPECT_EQ("{ 1, 2, 3 }", Print(b));
938 }
939 
TEST(PrintStlContainerTest,TwoDimensionalNativeArray)940 TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
941   const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
942   NativeArray<int[3]> b(a, 2, kReference);
943   EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
944 }
945 
946 // Tests that a class named iterator isn't treated as a container.
947 
948 struct iterator {
949   char x;
950 };
951 
TEST(PrintStlContainerTest,Iterator)952 TEST(PrintStlContainerTest, Iterator) {
953   iterator it = {};
954   EXPECT_EQ("1-byte object <00>", Print(it));
955 }
956 
957 // Tests that a class named const_iterator isn't treated as a container.
958 
959 struct const_iterator {
960   char x;
961 };
962 
TEST(PrintStlContainerTest,ConstIterator)963 TEST(PrintStlContainerTest, ConstIterator) {
964   const_iterator it = {};
965   EXPECT_EQ("1-byte object <00>", Print(it));
966 }
967 
968 #if GTEST_HAS_TR1_TUPLE
969 // Tests printing tuples.
970 
971 // Tuples of various arities.
TEST(PrintTupleTest,VariousSizes)972 TEST(PrintTupleTest, VariousSizes) {
973   tuple<> t0;
974   EXPECT_EQ("()", Print(t0));
975 
976   tuple<int> t1(5);
977   EXPECT_EQ("(5)", Print(t1));
978 
979   tuple<char, bool> t2('a', true);
980   EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
981 
982   tuple<bool, int, int> t3(false, 2, 3);
983   EXPECT_EQ("(false, 2, 3)", Print(t3));
984 
985   tuple<bool, int, int, int> t4(false, 2, 3, 4);
986   EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
987 
988   tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true);
989   EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5));
990 
991   tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6);
992   EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6));
993 
994   tuple<bool, int, int, int, bool, int, int> t7(false, 2, 3, 4, true, 6, 7);
995   EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7));
996 
997   tuple<bool, int, int, int, bool, int, int, bool> t8(
998       false, 2, 3, 4, true, 6, 7, true);
999   EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8));
1000 
1001   tuple<bool, int, int, int, bool, int, int, bool, int> t9(
1002       false, 2, 3, 4, true, 6, 7, true, 9);
1003   EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9));
1004 
1005   const char* const str = "8";
1006   // VC++ 2010's implementation of tuple of C++0x is deficient, requiring
1007   // an explicit type cast of NULL to be used.
1008   tuple<bool, char, short, testing::internal::Int32,  // NOLINT
1009       testing::internal::Int64, float, double, const char*, void*, string>
1010       t10(false, 'a', 3, 4, 5, 1.5F, -2.5, str,
1011           ImplicitCast_<void*>(NULL), "10");
1012   EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
1013             " pointing to \"8\", NULL, \"10\")",
1014             Print(t10));
1015 }
1016 
1017 // Nested tuples.
TEST(PrintTupleTest,NestedTuple)1018 TEST(PrintTupleTest, NestedTuple) {
1019   tuple<tuple<int, bool>, char> nested(make_tuple(5, true), 'a');
1020   EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
1021 }
1022 
1023 #endif  // GTEST_HAS_TR1_TUPLE
1024 
1025 // Tests printing user-defined unprintable types.
1026 
1027 // Unprintable types in the global namespace.
TEST(PrintUnprintableTypeTest,InGlobalNamespace)1028 TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
1029   EXPECT_EQ("1-byte object <00>",
1030             Print(UnprintableTemplateInGlobal<char>()));
1031 }
1032 
1033 // Unprintable types in a user namespace.
TEST(PrintUnprintableTypeTest,InUserNamespace)1034 TEST(PrintUnprintableTypeTest, InUserNamespace) {
1035   EXPECT_EQ("16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1036             Print(::foo::UnprintableInFoo()));
1037 }
1038 
1039 // Unprintable types are that too big to be printed completely.
1040 
1041 struct Big {
Bigtesting::gtest_printers_test::Big1042   Big() { memset(array, 0, sizeof(array)); }
1043   char array[257];
1044 };
1045 
TEST(PrintUnpritableTypeTest,BigObject)1046 TEST(PrintUnpritableTypeTest, BigObject) {
1047   EXPECT_EQ("257-byte object <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-00 00-00 "
1049             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1050             "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
1051             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1052             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1053             "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
1054             Print(Big()));
1055 }
1056 
1057 // Tests printing user-defined streamable types.
1058 
1059 // Streamable types in the global namespace.
TEST(PrintStreamableTypeTest,InGlobalNamespace)1060 TEST(PrintStreamableTypeTest, InGlobalNamespace) {
1061   StreamableInGlobal x;
1062   EXPECT_EQ("StreamableInGlobal", Print(x));
1063   EXPECT_EQ("StreamableInGlobal*", Print(&x));
1064 }
1065 
1066 // Printable template types in a user namespace.
TEST(PrintStreamableTypeTest,TemplateTypeInUserNamespace)1067 TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
1068   EXPECT_EQ("StreamableTemplateInFoo: 0",
1069             Print(::foo::StreamableTemplateInFoo<int>()));
1070 }
1071 
1072 // Tests printing user-defined types that have a PrintTo() function.
TEST(PrintPrintableTypeTest,InUserNamespace)1073 TEST(PrintPrintableTypeTest, InUserNamespace) {
1074   EXPECT_EQ("PrintableViaPrintTo: 0",
1075             Print(::foo::PrintableViaPrintTo()));
1076 }
1077 
1078 // Tests printing a pointer to a user-defined type that has a <<
1079 // operator for its pointer.
TEST(PrintPrintableTypeTest,PointerInUserNamespace)1080 TEST(PrintPrintableTypeTest, PointerInUserNamespace) {
1081   ::foo::PointerPrintable x;
1082   EXPECT_EQ("PointerPrintable*", Print(&x));
1083 }
1084 
1085 // Tests printing user-defined class template that have a PrintTo() function.
TEST(PrintPrintableTypeTest,TemplateInUserNamespace)1086 TEST(PrintPrintableTypeTest, TemplateInUserNamespace) {
1087   EXPECT_EQ("PrintableViaPrintToTemplate: 5",
1088             Print(::foo::PrintableViaPrintToTemplate<int>(5)));
1089 }
1090 
1091 #if GTEST_HAS_PROTOBUF_
1092 
1093 // Tests printing a protocol message.
TEST(PrintProtocolMessageTest,PrintsShortDebugString)1094 TEST(PrintProtocolMessageTest, PrintsShortDebugString) {
1095   testing::internal::TestMessage msg;
1096   msg.set_member("yes");
1097   EXPECT_EQ("<member:\"yes\">", Print(msg));
1098 }
1099 
1100 // Tests printing a short proto2 message.
TEST(PrintProto2MessageTest,PrintsShortDebugStringWhenItIsShort)1101 TEST(PrintProto2MessageTest, PrintsShortDebugStringWhenItIsShort) {
1102   testing::internal::FooMessage msg;
1103   msg.set_int_field(2);
1104   msg.set_string_field("hello");
1105   EXPECT_PRED2(RE::FullMatch, Print(msg),
1106                "<int_field:\\s*2\\s+string_field:\\s*\"hello\">");
1107 }
1108 
1109 // Tests printing a long proto2 message.
TEST(PrintProto2MessageTest,PrintsDebugStringWhenItIsLong)1110 TEST(PrintProto2MessageTest, PrintsDebugStringWhenItIsLong) {
1111   testing::internal::FooMessage msg;
1112   msg.set_int_field(2);
1113   msg.set_string_field("hello");
1114   msg.add_names("peter");
1115   msg.add_names("paul");
1116   msg.add_names("mary");
1117   EXPECT_PRED2(RE::FullMatch, Print(msg),
1118                "<\n"
1119                "int_field:\\s*2\n"
1120                "string_field:\\s*\"hello\"\n"
1121                "names:\\s*\"peter\"\n"
1122                "names:\\s*\"paul\"\n"
1123                "names:\\s*\"mary\"\n"
1124                ">");
1125 }
1126 
1127 #endif  // GTEST_HAS_PROTOBUF_
1128 
1129 // Tests that the universal printer prints both the address and the
1130 // value of a reference.
TEST(PrintReferenceTest,PrintsAddressAndValue)1131 TEST(PrintReferenceTest, PrintsAddressAndValue) {
1132   int n = 5;
1133   EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
1134 
1135   int a[2][3] = {
1136     { 0, 1, 2 },
1137     { 3, 4, 5 }
1138   };
1139   EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
1140             PrintByRef(a));
1141 
1142   const ::foo::UnprintableInFoo x;
1143   EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object "
1144             "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1145             PrintByRef(x));
1146 }
1147 
1148 // Tests that the universal printer prints a function pointer passed by
1149 // reference.
TEST(PrintReferenceTest,HandlesFunctionPointer)1150 TEST(PrintReferenceTest, HandlesFunctionPointer) {
1151   void (*fp)(int n) = &MyFunction;
1152   const string fp_pointer_string =
1153       PrintPointer(reinterpret_cast<const void*>(&fp));
1154   // We cannot directly cast &MyFunction to const void* because the
1155   // standard disallows casting between pointers to functions and
1156   // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
1157   // this limitation.
1158   const string fp_string = PrintPointer(reinterpret_cast<const void*>(
1159       reinterpret_cast<internal::BiggestInt>(fp)));
1160   EXPECT_EQ("@" + fp_pointer_string + " " + fp_string,
1161             PrintByRef(fp));
1162 }
1163 
1164 // Tests that the universal printer prints a member function pointer
1165 // passed by reference.
TEST(PrintReferenceTest,HandlesMemberFunctionPointer)1166 TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
1167   int (Foo::*p)(char ch) = &Foo::MyMethod;
1168   EXPECT_TRUE(HasPrefix(
1169       PrintByRef(p),
1170       "@" + PrintPointer(reinterpret_cast<const void*>(&p)) + " " +
1171           Print(sizeof(p)) + "-byte object "));
1172 
1173   char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
1174   EXPECT_TRUE(HasPrefix(
1175       PrintByRef(p2),
1176       "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) + " " +
1177           Print(sizeof(p2)) + "-byte object "));
1178 }
1179 
1180 // Tests that the universal printer prints a member variable pointer
1181 // passed by reference.
TEST(PrintReferenceTest,HandlesMemberVariablePointer)1182 TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
1183   int (Foo::*p) = &Foo::value;  // NOLINT
1184   EXPECT_TRUE(HasPrefix(
1185       PrintByRef(p),
1186       "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object "));
1187 }
1188 
1189 // Useful for testing PrintToString().  We cannot use EXPECT_EQ()
1190 // there as its implementation uses PrintToString().  The caller must
1191 // ensure that 'value' has no side effect.
1192 #define EXPECT_PRINT_TO_STRING_(value, expected_string)         \
1193   EXPECT_TRUE(PrintToString(value) == (expected_string))        \
1194       << " where " #value " prints as " << (PrintToString(value))
1195 
TEST(PrintToStringTest,WorksForScalar)1196 TEST(PrintToStringTest, WorksForScalar) {
1197   EXPECT_PRINT_TO_STRING_(123, "123");
1198 }
1199 
TEST(PrintToStringTest,WorksForPointerToConstChar)1200 TEST(PrintToStringTest, WorksForPointerToConstChar) {
1201   const char* p = "hello";
1202   EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1203 }
1204 
TEST(PrintToStringTest,WorksForPointerToNonConstChar)1205 TEST(PrintToStringTest, WorksForPointerToNonConstChar) {
1206   char s[] = "hello";
1207   char* p = s;
1208   EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1209 }
1210 
TEST(PrintToStringTest,WorksForArray)1211 TEST(PrintToStringTest, WorksForArray) {
1212   int n[3] = { 1, 2, 3 };
1213   EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }");
1214 }
1215 
1216 #undef EXPECT_PRINT_TO_STRING_
1217 
TEST(UniversalTersePrintTest,WorksForNonReference)1218 TEST(UniversalTersePrintTest, WorksForNonReference) {
1219   ::std::stringstream ss;
1220   UniversalTersePrint(123, &ss);
1221   EXPECT_EQ("123", ss.str());
1222 }
1223 
TEST(UniversalTersePrintTest,WorksForReference)1224 TEST(UniversalTersePrintTest, WorksForReference) {
1225   const int& n = 123;
1226   ::std::stringstream ss;
1227   UniversalTersePrint(n, &ss);
1228   EXPECT_EQ("123", ss.str());
1229 }
1230 
TEST(UniversalTersePrintTest,WorksForCString)1231 TEST(UniversalTersePrintTest, WorksForCString) {
1232   const char* s1 = "abc";
1233   ::std::stringstream ss1;
1234   UniversalTersePrint(s1, &ss1);
1235   EXPECT_EQ("\"abc\"", ss1.str());
1236 
1237   char* s2 = const_cast<char*>(s1);
1238   ::std::stringstream ss2;
1239   UniversalTersePrint(s2, &ss2);
1240   EXPECT_EQ("\"abc\"", ss2.str());
1241 
1242   const char* s3 = NULL;
1243   ::std::stringstream ss3;
1244   UniversalTersePrint(s3, &ss3);
1245   EXPECT_EQ("NULL", ss3.str());
1246 }
1247 
TEST(UniversalPrintTest,WorksForNonReference)1248 TEST(UniversalPrintTest, WorksForNonReference) {
1249   ::std::stringstream ss;
1250   UniversalPrint(123, &ss);
1251   EXPECT_EQ("123", ss.str());
1252 }
1253 
TEST(UniversalPrintTest,WorksForReference)1254 TEST(UniversalPrintTest, WorksForReference) {
1255   const int& n = 123;
1256   ::std::stringstream ss;
1257   UniversalPrint(n, &ss);
1258   EXPECT_EQ("123", ss.str());
1259 }
1260 
TEST(UniversalPrintTest,WorksForCString)1261 TEST(UniversalPrintTest, WorksForCString) {
1262   const char* s1 = "abc";
1263   ::std::stringstream ss1;
1264   UniversalPrint(s1, &ss1);
1265   EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", string(ss1.str()));
1266 
1267   char* s2 = const_cast<char*>(s1);
1268   ::std::stringstream ss2;
1269   UniversalPrint(s2, &ss2);
1270   EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", string(ss2.str()));
1271 
1272   const char* s3 = NULL;
1273   ::std::stringstream ss3;
1274   UniversalPrint(s3, &ss3);
1275   EXPECT_EQ("NULL", ss3.str());
1276 }
1277 
1278 
1279 #if GTEST_HAS_TR1_TUPLE
1280 
TEST(UniversalTersePrintTupleFieldsToStringsTest,PrintsEmptyTuple)1281 TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsEmptyTuple) {
1282   Strings result = UniversalTersePrintTupleFieldsToStrings(make_tuple());
1283   EXPECT_EQ(0u, result.size());
1284 }
1285 
TEST(UniversalTersePrintTupleFieldsToStringsTest,PrintsOneTuple)1286 TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsOneTuple) {
1287   Strings result = UniversalTersePrintTupleFieldsToStrings(make_tuple(1));
1288   ASSERT_EQ(1u, result.size());
1289   EXPECT_EQ("1", result[0]);
1290 }
1291 
TEST(UniversalTersePrintTupleFieldsToStringsTest,PrintsTwoTuple)1292 TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsTwoTuple) {
1293   Strings result = UniversalTersePrintTupleFieldsToStrings(make_tuple(1, 'a'));
1294   ASSERT_EQ(2u, result.size());
1295   EXPECT_EQ("1", result[0]);
1296   EXPECT_EQ("'a' (97, 0x61)", result[1]);
1297 }
1298 
TEST(UniversalTersePrintTupleFieldsToStringsTest,PrintsTersely)1299 TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsTersely) {
1300   const int n = 1;
1301   Strings result = UniversalTersePrintTupleFieldsToStrings(
1302       tuple<const int&, const char*>(n, "a"));
1303   ASSERT_EQ(2u, result.size());
1304   EXPECT_EQ("1", result[0]);
1305   EXPECT_EQ("\"a\"", result[1]);
1306 }
1307 
1308 #endif  // GTEST_HAS_TR1_TUPLE
1309 
1310 }  // namespace gtest_printers_test
1311 }  // namespace testing
1312