You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1566 lines
48 KiB

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