googletest-printers-test.cc 66 KB

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