googletest-printers-test.cc 61 KB

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