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