pretty_printers.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #pragma once
  2. #include <util/generic/string.h>
  3. #include <util/generic/strbuf.h>
  4. #include <util/generic/maybe.h>
  5. #include <util/generic/variant.h>
  6. #include <util/stream/output.h>
  7. #include <util/stream/str.h>
  8. #include <util/datetime/base.h>
  9. #include <gtest/gtest.h>
  10. #include <gmock/gmock.h>
  11. /**
  12. * Automatically define GTest pretty printer for type that can print itself to util's `IOutputStream`.
  13. *
  14. * Note that this macro should be instantiated in the same namespace as the type you're printing, otherwise
  15. * ADL will not find it.
  16. *
  17. * Example:
  18. *
  19. * We define a struct `TMyContainer` and an output operator that works with `IOutputStream`. We then use this macro
  20. * to automatically define GTest pretty printer:
  21. *
  22. * ```
  23. * namespace NMy {
  24. * struct TMyContainer {
  25. * int x, y;
  26. * };
  27. * }
  28. *
  29. * template <>
  30. * inline void Out<NMy::TMyContainer>(IOutputStream& stream, TTypeTraits<NMy::TMyContainer>::TFuncParam value) {
  31. * stream << "{ x=" << value.x << ", y=" << value.y << " }";
  32. * }
  33. *
  34. * namespace NMy {
  35. * Y_GTEST_ARCADIA_PRINTER(TMyContainer)
  36. * }
  37. * ```
  38. */
  39. #define Y_GTEST_ARCADIA_PRINTER(T) \
  40. void PrintTo(const T& value, std::ostream* stream) { \
  41. ::TString ss; \
  42. ::TStringOutput s{ss}; \
  43. s << value; \
  44. *stream << ss; \
  45. }
  46. template <typename TCharType, typename TCharTraits>
  47. void PrintTo(const TBasicString<TCharType, TCharTraits>& value, std::ostream* stream) {
  48. *stream << value.Quote().c_str();
  49. }
  50. template <typename TCharType, typename TCharTraits>
  51. void PrintTo(TBasicStringBuf<TCharType, TCharTraits> value, std::ostream* stream) {
  52. *stream << TBasicString<TCharType, TCharTraits>{value}.Quote().c_str();
  53. }
  54. template <typename T, typename P>
  55. void PrintTo(const TMaybe<T, P>& value, std::ostream* stream) {
  56. if (value.Defined()) {
  57. ::testing::internal::UniversalPrint(value.GetRef(), stream);
  58. } else {
  59. *stream << "nothing";
  60. }
  61. }
  62. inline void PrintTo(TNothing /* value */, std::ostream* stream) {
  63. *stream << "nothing";
  64. }
  65. inline void PrintTo(std::monostate /* value */, std::ostream* stream) {
  66. *stream << "monostate";
  67. }
  68. inline void PrintTo(TInstant value, std::ostream* stream) {
  69. *stream << value.ToString();
  70. }
  71. inline void PrintTo(TDuration value, std::ostream* stream) {
  72. *stream << value.ToString();
  73. }