aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/testing/gtest_extensions/pretty_printers.h
blob: 14d82844464f2c670b085f4592aa12f7b27e2856 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#pragma once

#include <util/generic/string.h>
#include <util/generic/strbuf.h>
#include <util/generic/maybe.h>
#include <util/generic/variant.h>
#include <util/stream/output.h>
#include <util/stream/str.h>
#include <util/datetime/base.h>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

/**
 * Automatically define GTest pretty printer for type that can print itself to util's `IOutputStream`.
 *
 * Note that this macro should be instantiated in the same namespace as the type you're printing, otherwise
 * ADL will not find it.
 *
 * Example:
 *
 * We define a struct `TMyContainer` and an output operator that works with `IOutputStream`. We then use this macro
 * to automatically define GTest pretty printer:
 *
 * ```
 * namespace NMy {
 *     struct TMyContainer {
 *         int x, y;
 *     };
 * }
 *
 * template <>
 * inline void Out<NMy::TMyContainer>(IOutputStream& stream, TTypeTraits<NMy::TMyContainer>::TFuncParam value) {
 *     stream << "{ x=" << value.x << ", y=" << value.y << " }";
 * }
 *
 * namespace NMy {
 *     Y_GTEST_ARCADIA_PRINTER(TMyContainer)
 * }
 * ```
 */
#define Y_GTEST_ARCADIA_PRINTER(T) \
    void PrintTo(const T& value, std::ostream* stream) {   \
        ::TString ss;                \
        ::TStringOutput s{ss};       \
        s << value;                  \
        *stream << ss;               \
    }


template <typename TCharType, typename TCharTraits>
void PrintTo(const TBasicString<TCharType, TCharTraits>& value, std::ostream* stream) {
    *stream << value.Quote().c_str();
}

template <typename TCharType, typename TCharTraits>
void PrintTo(TBasicStringBuf<TCharType, TCharTraits> value, std::ostream* stream) {
    *stream << TBasicString<TCharType, TCharTraits>{value}.Quote().c_str();
}

template <typename T, typename P>
void PrintTo(const TMaybe<T, P>& value, std::ostream* stream) {
    if (value.Defined()) {
        ::testing::internal::UniversalPrint(value.GetRef(), stream);
    } else {
        *stream << "nothing";
    }
}

inline void PrintTo(TNothing /* value */, std::ostream* stream) {
    *stream << "nothing";
}

inline void PrintTo(std::monostate /* value */, std::ostream* stream) {
    *stream << "monostate";
}

inline void PrintTo(TInstant value, std::ostream* stream) {
    *stream << value.ToString();
}

inline void PrintTo(TDuration value, std::ostream* stream) {
    *stream << value.ToString();
}