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 <stdexcept>
8#include <string>
9#include <vector>
10
11#include <userver/utils/not_null.hpp>
12#include <userver/utils/statistics/labels.hpp>
13#include <userver/utils/statistics/metric_value.hpp>
14#include <userver/utils/statistics/storage.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace utils::statistics {
19
20namespace impl {
21struct SnapshotData;
22} // namespace impl
23
24/// @brief Thrown by statistics::Snapshot queries on unexpected metrics states.
25class MetricQueryError final : public std::runtime_error {
26 public:
27 using std::runtime_error::runtime_error;
28};
29
30/// @brief A snapshot of metrics from utils::statistics::Storage.
31class Snapshot final {
32 public:
33 /// @brief Create a new snapshot of metrics with paths starting with @a prefix
34 /// and labels containing @a require_labels.
35 /// @throws std::exception if a metric writer throws.
36 explicit Snapshot(const Storage& storage, std::string prefix = {},
37 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,
49 std::vector<Label> require_labels = {}) const;
50
51 private:
52 friend void PrintTo(const Snapshot& data, std::ostream*);
53
54 Request request_;
55 utils::SharedRef<const impl::SnapshotData> data_;
56};
57
58/// @brief Support for gtest diagnostics for utils::statistics::Snapshot.
59///
60/// @warning Never check the printed value programmatically! The string is not
61/// stable and may change, depending on the version of stdlib and userver.
62///
63/// **Valid usage:**
64/// @code
65/// EXPECT_EQ(..., ...) << testing::PrintToString(snapshot);
66/// @endcode
67///
68/// **Invalid usage:**
69/// @code
70/// std::ostringstream stream;
71/// PrintTo(snapshot, &stream);
72/// EXPECT_EQ(stream.str(), ...);
73/// @endcode
74void PrintTo(const Snapshot& data, std::ostream*);
75
76} // namespace utils::statistics
77
78USERVER_NAMESPACE_END