gtest-printers.h 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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 implements a universal value printer that can print a
  32. // value of any type T:
  33. //
  34. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  35. //
  36. // A user can teach this function how to print a class type T by
  37. // defining either operator<<() or PrintTo() in the namespace that
  38. // defines T. More specifically, the FIRST defined function in the
  39. // following list will be used (assuming T is defined in namespace
  40. // foo):
  41. //
  42. // 1. foo::PrintTo(const T&, ostream*)
  43. // 2. operator<<(ostream&, const T&) defined in either foo or the
  44. // global namespace.
  45. //
  46. // However if T is an STL-style container then it is printed element-wise
  47. // unless foo::PrintTo(const T&, ostream*) is defined. Note that
  48. // operator<<() is ignored for container types.
  49. //
  50. // If none of the above is defined, it will print the debug string of
  51. // the value if it is a protocol buffer, or print the raw bytes in the
  52. // value otherwise.
  53. //
  54. // To aid debugging: when T is a reference type, the address of the
  55. // value is also printed; when T is a (const) char pointer, both the
  56. // pointer value and the NUL-terminated string it points to are
  57. // printed.
  58. //
  59. // We also provide some convenient wrappers:
  60. //
  61. // // Prints a value to a string. For a (const or not) char
  62. // // pointer, the NUL-terminated string (but not the pointer) is
  63. // // printed.
  64. // std::string ::testing::PrintToString(const T& value);
  65. //
  66. // // Prints a value tersely: for a reference type, the referenced
  67. // // value (but not the address) is printed; for a (const or not) char
  68. // // pointer, the NUL-terminated string (but not the pointer) is
  69. // // printed.
  70. // void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
  71. //
  72. // // Prints value using the type inferred by the compiler. The difference
  73. // // from UniversalTersePrint() is that this function prints both the
  74. // // pointer and the NUL-terminated string for a (const or not) char pointer.
  75. // void ::testing::internal::UniversalPrint(const T& value, ostream*);
  76. //
  77. // // Prints the fields of a tuple tersely to a string vector, one
  78. // // element for each field. Tuple support must be enabled in
  79. // // gtest-port.h.
  80. // std::vector<string> UniversalTersePrintTupleFieldsToStrings(
  81. // const Tuple& value);
  82. //
  83. // Known limitation:
  84. //
  85. // The print primitives print the elements of an STL-style container
  86. // using the compiler-inferred type of *iter where iter is a
  87. // const_iterator of the container. When const_iterator is an input
  88. // iterator but not a forward iterator, this inferred type may not
  89. // match value_type, and the print output may be incorrect. In
  90. // practice, this is rarely a problem as for most containers
  91. // const_iterator is a forward iterator. We'll fix this if there's an
  92. // actual need for it. Note that this fix cannot rely on value_type
  93. // being defined as many user-defined container types don't have
  94. // value_type.
  95. // GOOGLETEST_CM0001 DO NOT DELETE
  96. #ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
  97. #define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
  98. #include <ostream> // NOLINT
  99. #include <sstream>
  100. #include <string>
  101. #include <utility>
  102. #include <vector>
  103. #include "gtest/internal/gtest-port.h"
  104. #include "gtest/internal/gtest-internal.h"
  105. #if GTEST_HAS_STD_TUPLE_
  106. # include <tuple>
  107. #endif
  108. #if GTEST_HAS_ABSL
  109. #include "absl/strings/string_view.h"
  110. #include "absl/types/optional.h"
  111. #include "absl/types/variant.h"
  112. #endif // GTEST_HAS_ABSL
  113. namespace testing {
  114. // Definitions in the 'internal' and 'internal2' name spaces are
  115. // subject to change without notice. DO NOT USE THEM IN USER CODE!
  116. namespace internal2 {
  117. // Prints the given number of bytes in the given object to the given
  118. // ostream.
  119. GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
  120. size_t count,
  121. ::std::ostream* os);
  122. // For selecting which printer to use when a given type has neither <<
  123. // nor PrintTo().
  124. enum TypeKind {
  125. kProtobuf, // a protobuf type
  126. kConvertibleToInteger, // a type implicitly convertible to BiggestInt
  127. // (e.g. a named or unnamed enum type)
  128. #if GTEST_HAS_ABSL
  129. kConvertibleToStringView, // a type implicitly convertible to
  130. // absl::string_view
  131. #endif
  132. kOtherType // anything else
  133. };
  134. // TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called
  135. // by the universal printer to print a value of type T when neither
  136. // operator<< nor PrintTo() is defined for T, where kTypeKind is the
  137. // "kind" of T as defined by enum TypeKind.
  138. template <typename T, TypeKind kTypeKind>
  139. class TypeWithoutFormatter {
  140. public:
  141. // This default version is called when kTypeKind is kOtherType.
  142. static void PrintValue(const T& value, ::std::ostream* os) {
  143. PrintBytesInObjectTo(static_cast<const unsigned char*>(
  144. reinterpret_cast<const void*>(&value)),
  145. sizeof(value), os);
  146. }
  147. };
  148. // We print a protobuf using its ShortDebugString() when the string
  149. // doesn't exceed this many characters; otherwise we print it using
  150. // DebugString() for better readability.
  151. const size_t kProtobufOneLinerMaxLength = 50;
  152. template <typename T>
  153. class TypeWithoutFormatter<T, kProtobuf> {
  154. public:
  155. static void PrintValue(const T& value, ::std::ostream* os) {
  156. std::string pretty_str = value.ShortDebugString();
  157. if (pretty_str.length() > kProtobufOneLinerMaxLength) {
  158. pretty_str = "\n" + value.DebugString();
  159. }
  160. *os << ("<" + pretty_str + ">");
  161. }
  162. };
  163. template <typename T>
  164. class TypeWithoutFormatter<T, kConvertibleToInteger> {
  165. public:
  166. // Since T has no << operator or PrintTo() but can be implicitly
  167. // converted to BiggestInt, we print it as a BiggestInt.
  168. //
  169. // Most likely T is an enum type (either named or unnamed), in which
  170. // case printing it as an integer is the desired behavior. In case
  171. // T is not an enum, printing it as an integer is the best we can do
  172. // given that it has no user-defined printer.
  173. static void PrintValue(const T& value, ::std::ostream* os) {
  174. const internal::BiggestInt kBigInt = value;
  175. *os << kBigInt;
  176. }
  177. };
  178. #if GTEST_HAS_ABSL
  179. template <typename T>
  180. class TypeWithoutFormatter<T, kConvertibleToStringView> {
  181. public:
  182. // Since T has neither operator<< nor PrintTo() but can be implicitly
  183. // converted to absl::string_view, we print it as a absl::string_view.
  184. //
  185. // Note: the implementation is further below, as it depends on
  186. // internal::PrintTo symbol which is defined later in the file.
  187. static void PrintValue(const T& value, ::std::ostream* os);
  188. };
  189. #endif
  190. // Prints the given value to the given ostream. If the value is a
  191. // protocol message, its debug string is printed; if it's an enum or
  192. // of a type implicitly convertible to BiggestInt, it's printed as an
  193. // integer; otherwise the bytes in the value are printed. This is
  194. // what UniversalPrinter<T>::Print() does when it knows nothing about
  195. // type T and T has neither << operator nor PrintTo().
  196. //
  197. // A user can override this behavior for a class type Foo by defining
  198. // a << operator in the namespace where Foo is defined.
  199. //
  200. // We put this operator in namespace 'internal2' instead of 'internal'
  201. // to simplify the implementation, as much code in 'internal' needs to
  202. // use << in STL, which would conflict with our own << were it defined
  203. // in 'internal'.
  204. //
  205. // Note that this operator<< takes a generic std::basic_ostream<Char,
  206. // CharTraits> type instead of the more restricted std::ostream. If
  207. // we define it to take an std::ostream instead, we'll get an
  208. // "ambiguous overloads" compiler error when trying to print a type
  209. // Foo that supports streaming to std::basic_ostream<Char,
  210. // CharTraits>, as the compiler cannot tell whether
  211. // operator<<(std::ostream&, const T&) or
  212. // operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
  213. // specific.
  214. template <typename Char, typename CharTraits, typename T>
  215. ::std::basic_ostream<Char, CharTraits>& operator<<(
  216. ::std::basic_ostream<Char, CharTraits>& os, const T& x) {
  217. TypeWithoutFormatter<T, (internal::IsAProtocolMessage<T>::value
  218. ? kProtobuf
  219. : internal::ImplicitlyConvertible<
  220. const T&, internal::BiggestInt>::value
  221. ? kConvertibleToInteger
  222. :
  223. #if GTEST_HAS_ABSL
  224. internal::ImplicitlyConvertible<
  225. const T&, absl::string_view>::value
  226. ? kConvertibleToStringView
  227. :
  228. #endif
  229. kOtherType)>::PrintValue(x, &os);
  230. return os;
  231. }
  232. } // namespace internal2
  233. } // namespace testing
  234. // This namespace MUST NOT BE NESTED IN ::testing, or the name look-up
  235. // magic needed for implementing UniversalPrinter won't work.
  236. namespace testing_internal {
  237. // Used to print a value that is not an STL-style container when the
  238. // user doesn't define PrintTo() for it.
  239. template <typename T>
  240. void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) {
  241. // With the following statement, during unqualified name lookup,
  242. // testing::internal2::operator<< appears as if it was declared in
  243. // the nearest enclosing namespace that contains both
  244. // ::testing_internal and ::testing::internal2, i.e. the global
  245. // namespace. For more details, refer to the C++ Standard section
  246. // 7.3.4-1 [namespace.udir]. This allows us to fall back onto
  247. // testing::internal2::operator<< in case T doesn't come with a <<
  248. // operator.
  249. //
  250. // We cannot write 'using ::testing::internal2::operator<<;', which
  251. // gcc 3.3 fails to compile due to a compiler bug.
  252. using namespace ::testing::internal2; // NOLINT
  253. // Assuming T is defined in namespace foo, in the next statement,
  254. // the compiler will consider all of:
  255. //
  256. // 1. foo::operator<< (thanks to Koenig look-up),
  257. // 2. ::operator<< (as the current namespace is enclosed in ::),
  258. // 3. testing::internal2::operator<< (thanks to the using statement above).
  259. //
  260. // The operator<< whose type matches T best will be picked.
  261. //
  262. // We deliberately allow #2 to be a candidate, as sometimes it's
  263. // impossible to define #1 (e.g. when foo is ::std, defining
  264. // anything in it is undefined behavior unless you are a compiler
  265. // vendor.).
  266. *os << value;
  267. }
  268. } // namespace testing_internal
  269. namespace testing {
  270. namespace internal {
  271. // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
  272. // value of type ToPrint that is an operand of a comparison assertion
  273. // (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
  274. // the comparison, and is used to help determine the best way to
  275. // format the value. In particular, when the value is a C string
  276. // (char pointer) and the other operand is an STL string object, we
  277. // want to format the C string as a string, since we know it is
  278. // compared by value with the string object. If the value is a char
  279. // pointer but the other operand is not an STL string object, we don't
  280. // know whether the pointer is supposed to point to a NUL-terminated
  281. // string, and thus want to print it as a pointer to be safe.
  282. //
  283. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  284. // The default case.
  285. template <typename ToPrint, typename OtherOperand>
  286. class FormatForComparison {
  287. public:
  288. static ::std::string Format(const ToPrint& value) {
  289. return ::testing::PrintToString(value);
  290. }
  291. };
  292. // Array.
  293. template <typename ToPrint, size_t N, typename OtherOperand>
  294. class FormatForComparison<ToPrint[N], OtherOperand> {
  295. public:
  296. static ::std::string Format(const ToPrint* value) {
  297. return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
  298. }
  299. };
  300. // By default, print C string as pointers to be safe, as we don't know
  301. // whether they actually point to a NUL-terminated string.
  302. #define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \
  303. template <typename OtherOperand> \
  304. class FormatForComparison<CharType*, OtherOperand> { \
  305. public: \
  306. static ::std::string Format(CharType* value) { \
  307. return ::testing::PrintToString(static_cast<const void*>(value)); \
  308. } \
  309. }
  310. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
  311. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
  312. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
  313. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
  314. #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
  315. // If a C string is compared with an STL string object, we know it's meant
  316. // to point to a NUL-terminated string, and thus can print it as a string.
  317. #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
  318. template <> \
  319. class FormatForComparison<CharType*, OtherStringType> { \
  320. public: \
  321. static ::std::string Format(CharType* value) { \
  322. return ::testing::PrintToString(value); \
  323. } \
  324. }
  325. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
  326. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
  327. #if GTEST_HAS_GLOBAL_STRING
  328. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::string);
  329. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::string);
  330. #endif
  331. #if GTEST_HAS_GLOBAL_WSTRING
  332. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::wstring);
  333. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::wstring);
  334. #endif
  335. #if GTEST_HAS_STD_WSTRING
  336. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
  337. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
  338. #endif
  339. #undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
  340. // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
  341. // operand to be used in a failure message. The type (but not value)
  342. // of the other operand may affect the format. This allows us to
  343. // print a char* as a raw pointer when it is compared against another
  344. // char* or void*, and print it as a C string when it is compared
  345. // against an std::string object, for example.
  346. //
  347. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  348. template <typename T1, typename T2>
  349. std::string FormatForComparisonFailureMessage(
  350. const T1& value, const T2& /* other_operand */) {
  351. return FormatForComparison<T1, T2>::Format(value);
  352. }
  353. // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
  354. // value to the given ostream. The caller must ensure that
  355. // 'ostream_ptr' is not NULL, or the behavior is undefined.
  356. //
  357. // We define UniversalPrinter as a class template (as opposed to a
  358. // function template), as we need to partially specialize it for
  359. // reference types, which cannot be done with function templates.
  360. template <typename T>
  361. class UniversalPrinter;
  362. template <typename T>
  363. void UniversalPrint(const T& value, ::std::ostream* os);
  364. enum DefaultPrinterType {
  365. kPrintContainer,
  366. kPrintPointer,
  367. kPrintFunctionPointer,
  368. kPrintOther,
  369. };
  370. template <DefaultPrinterType type> struct WrapPrinterType {};
  371. // Used to print an STL-style container when the user doesn't define
  372. // a PrintTo() for it.
  373. template <typename C>
  374. void DefaultPrintTo(WrapPrinterType<kPrintContainer> /* dummy */,
  375. const C& container, ::std::ostream* os) {
  376. const size_t kMaxCount = 32; // The maximum number of elements to print.
  377. *os << '{';
  378. size_t count = 0;
  379. for (typename C::const_iterator it = container.begin();
  380. it != container.end(); ++it, ++count) {
  381. if (count > 0) {
  382. *os << ',';
  383. if (count == kMaxCount) { // Enough has been printed.
  384. *os << " ...";
  385. break;
  386. }
  387. }
  388. *os << ' ';
  389. // We cannot call PrintTo(*it, os) here as PrintTo() doesn't
  390. // handle *it being a native array.
  391. internal::UniversalPrint(*it, os);
  392. }
  393. if (count > 0) {
  394. *os << ' ';
  395. }
  396. *os << '}';
  397. }
  398. // Used to print a pointer that is neither a char pointer nor a member
  399. // pointer, when the user doesn't define PrintTo() for it. (A member
  400. // variable pointer or member function pointer doesn't really point to
  401. // a location in the address space. Their representation is
  402. // implementation-defined. Therefore they will be printed as raw
  403. // bytes.)
  404. template <typename T>
  405. void DefaultPrintTo(WrapPrinterType<kPrintPointer> /* dummy */,
  406. T* p, ::std::ostream* os) {
  407. if (p == NULL) {
  408. *os << "NULL";
  409. } else {
  410. // T is not a function type. We just call << to print p,
  411. // relying on ADL to pick up user-defined << for their pointer
  412. // types, if any.
  413. *os << p;
  414. }
  415. }
  416. template <typename T>
  417. void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */,
  418. T* p, ::std::ostream* os) {
  419. if (p == NULL) {
  420. *os << "NULL";
  421. } else {
  422. // T is a function type, so '*os << p' doesn't do what we want
  423. // (it just prints p as bool). We want to print p as a const
  424. // void*.
  425. *os << reinterpret_cast<const void*>(p);
  426. }
  427. }
  428. // Used to print a non-container, non-pointer value when the user
  429. // doesn't define PrintTo() for it.
  430. template <typename T>
  431. void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
  432. const T& value, ::std::ostream* os) {
  433. ::testing_internal::DefaultPrintNonContainerTo(value, os);
  434. }
  435. // Prints the given value using the << operator if it has one;
  436. // otherwise prints the bytes in it. This is what
  437. // UniversalPrinter<T>::Print() does when PrintTo() is not specialized
  438. // or overloaded for type T.
  439. //
  440. // A user can override this behavior for a class type Foo by defining
  441. // an overload of PrintTo() in the namespace where Foo is defined. We
  442. // give the user this option as sometimes defining a << operator for
  443. // Foo is not desirable (e.g. the coding style may prevent doing it,
  444. // or there is already a << operator but it doesn't do what the user
  445. // wants).
  446. template <typename T>
  447. void PrintTo(const T& value, ::std::ostream* os) {
  448. // DefaultPrintTo() is overloaded. The type of its first argument
  449. // determines which version will be picked.
  450. //
  451. // Note that we check for container types here, prior to we check
  452. // for protocol message types in our operator<<. The rationale is:
  453. //
  454. // For protocol messages, we want to give people a chance to
  455. // override Google Mock's format by defining a PrintTo() or
  456. // operator<<. For STL containers, other formats can be
  457. // incompatible with Google Mock's format for the container
  458. // elements; therefore we check for container types here to ensure
  459. // that our format is used.
  460. //
  461. // Note that MSVC and clang-cl do allow an implicit conversion from
  462. // pointer-to-function to pointer-to-object, but clang-cl warns on it.
  463. // So don't use ImplicitlyConvertible if it can be helped since it will
  464. // cause this warning, and use a separate overload of DefaultPrintTo for
  465. // function pointers so that the `*os << p` in the object pointer overload
  466. // doesn't cause that warning either.
  467. DefaultPrintTo(
  468. WrapPrinterType <
  469. (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
  470. !IsRecursiveContainer<T>::value
  471. ? kPrintContainer
  472. : !is_pointer<T>::value
  473. ? kPrintOther
  474. #if GTEST_LANG_CXX11
  475. : std::is_function<typename std::remove_pointer<T>::type>::value
  476. #else
  477. : !internal::ImplicitlyConvertible<T, const void*>::value
  478. #endif
  479. ? kPrintFunctionPointer
  480. : kPrintPointer > (),
  481. value, os);
  482. }
  483. // The following list of PrintTo() overloads tells
  484. // UniversalPrinter<T>::Print() how to print standard types (built-in
  485. // types, strings, plain arrays, and pointers).
  486. // Overloads for various char types.
  487. GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
  488. GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
  489. inline void PrintTo(char c, ::std::ostream* os) {
  490. // When printing a plain char, we always treat it as unsigned. This
  491. // way, the output won't be affected by whether the compiler thinks
  492. // char is signed or not.
  493. PrintTo(static_cast<unsigned char>(c), os);
  494. }
  495. // Overloads for other simple built-in types.
  496. inline void PrintTo(bool x, ::std::ostream* os) {
  497. *os << (x ? "true" : "false");
  498. }
  499. // Overload for wchar_t type.
  500. // Prints a wchar_t as a symbol if it is printable or as its internal
  501. // code otherwise and also as its decimal code (except for L'\0').
  502. // The L'\0' char is printed as "L'\\0'". The decimal code is printed
  503. // as signed integer when wchar_t is implemented by the compiler
  504. // as a signed type and is printed as an unsigned integer when wchar_t
  505. // is implemented as an unsigned type.
  506. GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
  507. // Overloads for C strings.
  508. GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
  509. inline void PrintTo(char* s, ::std::ostream* os) {
  510. PrintTo(ImplicitCast_<const char*>(s), os);
  511. }
  512. // signed/unsigned char is often used for representing binary data, so
  513. // we print pointers to it as void* to be safe.
  514. inline void PrintTo(const signed char* s, ::std::ostream* os) {
  515. PrintTo(ImplicitCast_<const void*>(s), os);
  516. }
  517. inline void PrintTo(signed char* s, ::std::ostream* os) {
  518. PrintTo(ImplicitCast_<const void*>(s), os);
  519. }
  520. inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
  521. PrintTo(ImplicitCast_<const void*>(s), os);
  522. }
  523. inline void PrintTo(unsigned char* s, ::std::ostream* os) {
  524. PrintTo(ImplicitCast_<const void*>(s), os);
  525. }
  526. // MSVC can be configured to define wchar_t as a typedef of unsigned
  527. // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
  528. // type. When wchar_t is a typedef, defining an overload for const
  529. // wchar_t* would cause unsigned short* be printed as a wide string,
  530. // possibly causing invalid memory accesses.
  531. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  532. // Overloads for wide C strings
  533. GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
  534. inline void PrintTo(wchar_t* s, ::std::ostream* os) {
  535. PrintTo(ImplicitCast_<const wchar_t*>(s), os);
  536. }
  537. #endif
  538. // Overload for C arrays. Multi-dimensional arrays are printed
  539. // properly.
  540. // Prints the given number of elements in an array, without printing
  541. // the curly braces.
  542. template <typename T>
  543. void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
  544. UniversalPrint(a[0], os);
  545. for (size_t i = 1; i != count; i++) {
  546. *os << ", ";
  547. UniversalPrint(a[i], os);
  548. }
  549. }
  550. // Overloads for ::string and ::std::string.
  551. #if GTEST_HAS_GLOBAL_STRING
  552. GTEST_API_ void PrintStringTo(const ::string&s, ::std::ostream* os);
  553. inline void PrintTo(const ::string& s, ::std::ostream* os) {
  554. PrintStringTo(s, os);
  555. }
  556. #endif // GTEST_HAS_GLOBAL_STRING
  557. GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
  558. inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
  559. PrintStringTo(s, os);
  560. }
  561. // Overloads for ::wstring and ::std::wstring.
  562. #if GTEST_HAS_GLOBAL_WSTRING
  563. GTEST_API_ void PrintWideStringTo(const ::wstring&s, ::std::ostream* os);
  564. inline void PrintTo(const ::wstring& s, ::std::ostream* os) {
  565. PrintWideStringTo(s, os);
  566. }
  567. #endif // GTEST_HAS_GLOBAL_WSTRING
  568. #if GTEST_HAS_STD_WSTRING
  569. GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
  570. inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
  571. PrintWideStringTo(s, os);
  572. }
  573. #endif // GTEST_HAS_STD_WSTRING
  574. #if GTEST_HAS_ABSL
  575. // Overload for absl::string_view.
  576. inline void PrintTo(absl::string_view sp, ::std::ostream* os) {
  577. PrintTo(::std::string(sp), os);
  578. }
  579. #endif // GTEST_HAS_ABSL
  580. #if GTEST_LANG_CXX11
  581. inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
  582. #endif // GTEST_LANG_CXX11
  583. #if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
  584. // Helper function for printing a tuple. T must be instantiated with
  585. // a tuple type.
  586. template <typename T>
  587. void PrintTupleTo(const T& t, ::std::ostream* os);
  588. #endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
  589. #if GTEST_HAS_TR1_TUPLE
  590. // Overload for ::std::tr1::tuple. Needed for printing function arguments,
  591. // which are packed as tuples.
  592. // Overloaded PrintTo() for tuples of various arities. We support
  593. // tuples of up-to 10 fields. The following implementation works
  594. // regardless of whether tr1::tuple is implemented using the
  595. // non-standard variadic template feature or not.
  596. inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) {
  597. PrintTupleTo(t, os);
  598. }
  599. template <typename T1>
  600. void PrintTo(const ::std::tr1::tuple<T1>& t, ::std::ostream* os) {
  601. PrintTupleTo(t, os);
  602. }
  603. template <typename T1, typename T2>
  604. void PrintTo(const ::std::tr1::tuple<T1, T2>& t, ::std::ostream* os) {
  605. PrintTupleTo(t, os);
  606. }
  607. template <typename T1, typename T2, typename T3>
  608. void PrintTo(const ::std::tr1::tuple<T1, T2, T3>& t, ::std::ostream* os) {
  609. PrintTupleTo(t, os);
  610. }
  611. template <typename T1, typename T2, typename T3, typename T4>
  612. void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4>& t, ::std::ostream* os) {
  613. PrintTupleTo(t, os);
  614. }
  615. template <typename T1, typename T2, typename T3, typename T4, typename T5>
  616. void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5>& t,
  617. ::std::ostream* os) {
  618. PrintTupleTo(t, os);
  619. }
  620. template <typename T1, typename T2, typename T3, typename T4, typename T5,
  621. typename T6>
  622. void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6>& t,
  623. ::std::ostream* os) {
  624. PrintTupleTo(t, os);
  625. }
  626. template <typename T1, typename T2, typename T3, typename T4, typename T5,
  627. typename T6, typename T7>
  628. void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7>& t,
  629. ::std::ostream* os) {
  630. PrintTupleTo(t, os);
  631. }
  632. template <typename T1, typename T2, typename T3, typename T4, typename T5,
  633. typename T6, typename T7, typename T8>
  634. void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8>& t,
  635. ::std::ostream* os) {
  636. PrintTupleTo(t, os);
  637. }
  638. template <typename T1, typename T2, typename T3, typename T4, typename T5,
  639. typename T6, typename T7, typename T8, typename T9>
  640. void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>& t,
  641. ::std::ostream* os) {
  642. PrintTupleTo(t, os);
  643. }
  644. template <typename T1, typename T2, typename T3, typename T4, typename T5,
  645. typename T6, typename T7, typename T8, typename T9, typename T10>
  646. void PrintTo(
  647. const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& t,
  648. ::std::ostream* os) {
  649. PrintTupleTo(t, os);
  650. }
  651. #endif // GTEST_HAS_TR1_TUPLE
  652. #if GTEST_HAS_STD_TUPLE_
  653. template <typename... Types>
  654. void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
  655. PrintTupleTo(t, os);
  656. }
  657. #endif // GTEST_HAS_STD_TUPLE_
  658. // Overload for std::pair.
  659. template <typename T1, typename T2>
  660. void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
  661. *os << '(';
  662. // We cannot use UniversalPrint(value.first, os) here, as T1 may be
  663. // a reference type. The same for printing value.second.
  664. UniversalPrinter<T1>::Print(value.first, os);
  665. *os << ", ";
  666. UniversalPrinter<T2>::Print(value.second, os);
  667. *os << ')';
  668. }
  669. // Implements printing a non-reference type T by letting the compiler
  670. // pick the right overload of PrintTo() for T.
  671. template <typename T>
  672. class UniversalPrinter {
  673. public:
  674. // MSVC warns about adding const to a function type, so we want to
  675. // disable the warning.
  676. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
  677. // Note: we deliberately don't call this PrintTo(), as that name
  678. // conflicts with ::testing::internal::PrintTo in the body of the
  679. // function.
  680. static void Print(const T& value, ::std::ostream* os) {
  681. // By default, ::testing::internal::PrintTo() is used for printing
  682. // the value.
  683. //
  684. // Thanks to Koenig look-up, if T is a class and has its own
  685. // PrintTo() function defined in its namespace, that function will
  686. // be visible here. Since it is more specific than the generic ones
  687. // in ::testing::internal, it will be picked by the compiler in the
  688. // following statement - exactly what we want.
  689. PrintTo(value, os);
  690. }
  691. GTEST_DISABLE_MSC_WARNINGS_POP_()
  692. };
  693. #if GTEST_HAS_ABSL
  694. // Printer for absl::optional
  695. template <typename T>
  696. class UniversalPrinter<::absl::optional<T>> {
  697. public:
  698. static void Print(const ::absl::optional<T>& value, ::std::ostream* os) {
  699. *os << '(';
  700. if (!value) {
  701. *os << "nullopt";
  702. } else {
  703. UniversalPrint(*value, os);
  704. }
  705. *os << ')';
  706. }
  707. };
  708. // Printer for absl::variant
  709. template <typename... T>
  710. class UniversalPrinter<::absl::variant<T...>> {
  711. public:
  712. static void Print(const ::absl::variant<T...>& value, ::std::ostream* os) {
  713. *os << '(';
  714. absl::visit(Visitor{os}, value);
  715. *os << ')';
  716. }
  717. private:
  718. struct Visitor {
  719. template <typename U>
  720. void operator()(const U& u) const {
  721. *os << "'" << GetTypeName<U>() << "' with value ";
  722. UniversalPrint(u, os);
  723. }
  724. ::std::ostream* os;
  725. };
  726. };
  727. #endif // GTEST_HAS_ABSL
  728. // UniversalPrintArray(begin, len, os) prints an array of 'len'
  729. // elements, starting at address 'begin'.
  730. template <typename T>
  731. void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
  732. if (len == 0) {
  733. *os << "{}";
  734. } else {
  735. *os << "{ ";
  736. const size_t kThreshold = 18;
  737. const size_t kChunkSize = 8;
  738. // If the array has more than kThreshold elements, we'll have to
  739. // omit some details by printing only the first and the last
  740. // kChunkSize elements.
  741. // FIXME: let the user control the threshold using a flag.
  742. if (len <= kThreshold) {
  743. PrintRawArrayTo(begin, len, os);
  744. } else {
  745. PrintRawArrayTo(begin, kChunkSize, os);
  746. *os << ", ..., ";
  747. PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
  748. }
  749. *os << " }";
  750. }
  751. }
  752. // This overload prints a (const) char array compactly.
  753. GTEST_API_ void UniversalPrintArray(
  754. const char* begin, size_t len, ::std::ostream* os);
  755. // This overload prints a (const) wchar_t array compactly.
  756. GTEST_API_ void UniversalPrintArray(
  757. const wchar_t* begin, size_t len, ::std::ostream* os);
  758. // Implements printing an array type T[N].
  759. template <typename T, size_t N>
  760. class UniversalPrinter<T[N]> {
  761. public:
  762. // Prints the given array, omitting some elements when there are too
  763. // many.
  764. static void Print(const T (&a)[N], ::std::ostream* os) {
  765. UniversalPrintArray(a, N, os);
  766. }
  767. };
  768. // Implements printing a reference type T&.
  769. template <typename T>
  770. class UniversalPrinter<T&> {
  771. public:
  772. // MSVC warns about adding const to a function type, so we want to
  773. // disable the warning.
  774. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
  775. static void Print(const T& value, ::std::ostream* os) {
  776. // Prints the address of the value. We use reinterpret_cast here
  777. // as static_cast doesn't compile when T is a function type.
  778. *os << "@" << reinterpret_cast<const void*>(&value) << " ";
  779. // Then prints the value itself.
  780. UniversalPrint(value, os);
  781. }
  782. GTEST_DISABLE_MSC_WARNINGS_POP_()
  783. };
  784. // Prints a value tersely: for a reference type, the referenced value
  785. // (but not the address) is printed; for a (const) char pointer, the
  786. // NUL-terminated string (but not the pointer) is printed.
  787. template <typename T>
  788. class UniversalTersePrinter {
  789. public:
  790. static void Print(const T& value, ::std::ostream* os) {
  791. UniversalPrint(value, os);
  792. }
  793. };
  794. template <typename T>
  795. class UniversalTersePrinter<T&> {
  796. public:
  797. static void Print(const T& value, ::std::ostream* os) {
  798. UniversalPrint(value, os);
  799. }
  800. };
  801. template <typename T, size_t N>
  802. class UniversalTersePrinter<T[N]> {
  803. public:
  804. static void Print(const T (&value)[N], ::std::ostream* os) {
  805. UniversalPrinter<T[N]>::Print(value, os);
  806. }
  807. };
  808. template <>
  809. class UniversalTersePrinter<const char*> {
  810. public:
  811. static void Print(const char* str, ::std::ostream* os) {
  812. if (str == NULL) {
  813. *os << "NULL";
  814. } else {
  815. UniversalPrint(std::string(str), os);
  816. }
  817. }
  818. };
  819. template <>
  820. class UniversalTersePrinter<char*> {
  821. public:
  822. static void Print(char* str, ::std::ostream* os) {
  823. UniversalTersePrinter<const char*>::Print(str, os);
  824. }
  825. };
  826. #if GTEST_HAS_STD_WSTRING
  827. template <>
  828. class UniversalTersePrinter<const wchar_t*> {
  829. public:
  830. static void Print(const wchar_t* str, ::std::ostream* os) {
  831. if (str == NULL) {
  832. *os << "NULL";
  833. } else {
  834. UniversalPrint(::std::wstring(str), os);
  835. }
  836. }
  837. };
  838. #endif
  839. template <>
  840. class UniversalTersePrinter<wchar_t*> {
  841. public:
  842. static void Print(wchar_t* str, ::std::ostream* os) {
  843. UniversalTersePrinter<const wchar_t*>::Print(str, os);
  844. }
  845. };
  846. template <typename T>
  847. void UniversalTersePrint(const T& value, ::std::ostream* os) {
  848. UniversalTersePrinter<T>::Print(value, os);
  849. }
  850. // Prints a value using the type inferred by the compiler. The
  851. // difference between this and UniversalTersePrint() is that for a
  852. // (const) char pointer, this prints both the pointer and the
  853. // NUL-terminated string.
  854. template <typename T>
  855. void UniversalPrint(const T& value, ::std::ostream* os) {
  856. // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
  857. // UniversalPrinter with T directly.
  858. typedef T T1;
  859. UniversalPrinter<T1>::Print(value, os);
  860. }
  861. typedef ::std::vector< ::std::string> Strings;
  862. // TuplePolicy<TupleT> must provide:
  863. // - tuple_size
  864. // size of tuple TupleT.
  865. // - get<size_t I>(const TupleT& t)
  866. // static function extracting element I of tuple TupleT.
  867. // - tuple_element<size_t I>::type
  868. // type of element I of tuple TupleT.
  869. template <typename TupleT>
  870. struct TuplePolicy;
  871. #if GTEST_HAS_TR1_TUPLE
  872. template <typename TupleT>
  873. struct TuplePolicy {
  874. typedef TupleT Tuple;
  875. static const size_t tuple_size = ::std::tr1::tuple_size<Tuple>::value;
  876. template <size_t I>
  877. struct tuple_element : ::std::tr1::tuple_element<static_cast<int>(I), Tuple> {
  878. };
  879. template <size_t I>
  880. static typename AddReference<const typename ::std::tr1::tuple_element<
  881. static_cast<int>(I), Tuple>::type>::type
  882. get(const Tuple& tuple) {
  883. return ::std::tr1::get<I>(tuple);
  884. }
  885. };
  886. template <typename TupleT>
  887. const size_t TuplePolicy<TupleT>::tuple_size;
  888. #endif // GTEST_HAS_TR1_TUPLE
  889. #if GTEST_HAS_STD_TUPLE_
  890. template <typename... Types>
  891. struct TuplePolicy< ::std::tuple<Types...> > {
  892. typedef ::std::tuple<Types...> Tuple;
  893. static const size_t tuple_size = ::std::tuple_size<Tuple>::value;
  894. template <size_t I>
  895. struct tuple_element : ::std::tuple_element<I, Tuple> {};
  896. template <size_t I>
  897. static const typename ::std::tuple_element<I, Tuple>::type& get(
  898. const Tuple& tuple) {
  899. return ::std::get<I>(tuple);
  900. }
  901. };
  902. template <typename... Types>
  903. const size_t TuplePolicy< ::std::tuple<Types...> >::tuple_size;
  904. #endif // GTEST_HAS_STD_TUPLE_
  905. #if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
  906. // This helper template allows PrintTo() for tuples and
  907. // UniversalTersePrintTupleFieldsToStrings() to be defined by
  908. // induction on the number of tuple fields. The idea is that
  909. // TuplePrefixPrinter<N>::PrintPrefixTo(t, os) prints the first N
  910. // fields in tuple t, and can be defined in terms of
  911. // TuplePrefixPrinter<N - 1>.
  912. //
  913. // The inductive case.
  914. template <size_t N>
  915. struct TuplePrefixPrinter {
  916. // Prints the first N fields of a tuple.
  917. template <typename Tuple>
  918. static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) {
  919. TuplePrefixPrinter<N - 1>::PrintPrefixTo(t, os);
  920. GTEST_INTENTIONAL_CONST_COND_PUSH_()
  921. if (N > 1) {
  922. GTEST_INTENTIONAL_CONST_COND_POP_()
  923. *os << ", ";
  924. }
  925. UniversalPrinter<
  926. typename TuplePolicy<Tuple>::template tuple_element<N - 1>::type>
  927. ::Print(TuplePolicy<Tuple>::template get<N - 1>(t), os);
  928. }
  929. // Tersely prints the first N fields of a tuple to a string vector,
  930. // one element for each field.
  931. template <typename Tuple>
  932. static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) {
  933. TuplePrefixPrinter<N - 1>::TersePrintPrefixToStrings(t, strings);
  934. ::std::stringstream ss;
  935. UniversalTersePrint(TuplePolicy<Tuple>::template get<N - 1>(t), &ss);
  936. strings->push_back(ss.str());
  937. }
  938. };
  939. // Base case.
  940. template <>
  941. struct TuplePrefixPrinter<0> {
  942. template <typename Tuple>
  943. static void PrintPrefixTo(const Tuple&, ::std::ostream*) {}
  944. template <typename Tuple>
  945. static void TersePrintPrefixToStrings(const Tuple&, Strings*) {}
  946. };
  947. // Helper function for printing a tuple.
  948. // Tuple must be either std::tr1::tuple or std::tuple type.
  949. template <typename Tuple>
  950. void PrintTupleTo(const Tuple& t, ::std::ostream* os) {
  951. *os << "(";
  952. TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::PrintPrefixTo(t, os);
  953. *os << ")";
  954. }
  955. // Prints the fields of a tuple tersely to a string vector, one
  956. // element for each field. See the comment before
  957. // UniversalTersePrint() for how we define "tersely".
  958. template <typename Tuple>
  959. Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
  960. Strings result;
  961. TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::
  962. TersePrintPrefixToStrings(value, &result);
  963. return result;
  964. }
  965. #endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
  966. } // namespace internal
  967. #if GTEST_HAS_ABSL
  968. namespace internal2 {
  969. template <typename T>
  970. void TypeWithoutFormatter<T, kConvertibleToStringView>::PrintValue(
  971. const T& value, ::std::ostream* os) {
  972. internal::PrintTo(absl::string_view(value), os);
  973. }
  974. } // namespace internal2
  975. #endif
  976. template <typename T>
  977. ::std::string PrintToString(const T& value) {
  978. ::std::stringstream ss;
  979. internal::UniversalTersePrinter<T>::Print(value, &ss);
  980. return ss.str();
  981. }
  982. } // namespace testing
  983. // Include any custom printer added by the local installation.
  984. // We must include this header at the end to make sure it can use the
  985. // declarations from this file.
  986. #include "gtest/internal/custom/gtest-printers.h"
  987. #endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_