googletest-printers-test.cc 64 KB

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