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.

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