userver: userver/utils/statistics/testing.hpp Source File
Loading...
Searching...
No Matches
testing.hpp
1#pragma once
2
3/// @file userver/utils/statistics/testing_utils.hpp
4/// @brief Utilities for analyzing emitted metrics in unit tests
5
6#include <iosfwd>
7#include <optional>
8#include <stdexcept>
9#include <string>
10#include <vector>
11
12#include <userver/utils/not_null.hpp>
13#include <userver/utils/statistics/labels.hpp>
14#include <userver/utils/statistics/metric_value.hpp>
15#include <userver/utils/statistics/storage.hpp>
16
17USERVER_NAMESPACE_BEGIN
18
19namespace utils::statistics {
20
21namespace impl {
22struct SnapshotData;
23} // namespace impl
24
25/// @brief Thrown by statistics::Snapshot queries on unexpected metrics states.
26class MetricQueryError final : public std::runtime_error {
27public:
28 using std::runtime_error::runtime_error;
29};
30
31/// @brief A snapshot of metrics from utils::statistics::Storage.
32class Snapshot final {
33public:
34 /// @brief Create a new snapshot of metrics with paths starting with @a prefix
35 /// and labels containing @a require_labels.
36 /// @throws std::exception if a metric writer throws.
37 explicit Snapshot(const Storage& storage, std::string prefix = {}, std::vector<Label> require_labels = {});
38
39 Snapshot(const Snapshot& other) = default;
40 Snapshot(Snapshot&& other) noexcept = default;
41
42 /// @brief Find a single metric by the given filter.
43 /// @param path The path of the target metric. `prefix` specified in the
44 /// constructor is prepended to the path.
45 /// @param require_labels Labels that the target metric should have.
46 /// @returns The value of the single found metric.
47 /// @throws MetricQueryError if none or multiple metrics are found.
48 MetricValue SingleMetric(std::string path, std::vector<Label> require_labels = {}) const;
49
50 /// @overload
51 std::optional<MetricValue> SingleMetricOptional(std::string path, std::vector<Label> require_labels = {}) const;
52
53private:
54 friend void PrintTo(const Snapshot& data, std::ostream*);
55
56 Request request_;
57 utils::SharedRef<const impl::SnapshotData> data_;
58};
59
60/// @brief Support for gtest diagnostics for utils::statistics::Snapshot.
61///
62/// @warning Never check the printed value programmatically! The string is not
63/// stable and may change, depending on the version of stdlib and userver.
64///
65/// **Valid usage:**
66/// @code
67/// EXPECT_EQ(..., ...) << testing::PrintToString(snapshot);
68/// @endcode
69///
70/// **Invalid usage:**
71/// @code
72/// std::ostringstream stream;
73/// PrintTo(snapshot, &stream);
74/// EXPECT_EQ(stream.str(), ...);
75/// @endcode
76void PrintTo(const Snapshot& data, std::ostream*);
77
78/// @brief Support for gtest diagnostics for utils::statistics::MetricValue.
79void PrintTo(MetricValue value, std::ostream*);
80
81} // namespace utils::statistics
82
83USERVER_NAMESPACE_END