userver: userver/utils/statistics/testing.hpp Source File
⚠️ This is the documentation for an old userver version. Click here to switch to the latest version.
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
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 friend std::ostream& operator<<(std::ostream&, const Snapshot& data);
54
55 Request request_;
56 utils::SharedRef<const impl::SnapshotData> data_;
57};
58
59// Support for PrintTo method in google tests
60void PrintTo(const Snapshot& data, std::ostream*);
61std::ostream& operator<<(std::ostream&, const Snapshot& data);
62
63} // namespace utils::statistics
64
65USERVER_NAMESPACE_END