userver: userver/storages/redis/mock_publish_waiter.hpp Source File
Loading...
Searching...
No Matches
mock_publish_waiter.hpp
1#pragma once
2
3#include <string>
4
7#include <userver/storages/redis/mock_client_google.hpp>
9
10USERVER_NAMESPACE_BEGIN
11
12namespace storages::redis {
13
14// This is very simple waiter class. It expects one - and exactly one
15// Publish call on redis gmock that should match given matcher. And calling
16// Wait() will ensure that this call did indeed happened.
17// Basic usage is like this:
18// auto my_redis_mock = GetRedisMock();
19// MockPublishWaiter waiter(
20// my_redis_mock,
21// "my-channel",
22// StartsWith("my-channel"));
23//
24// DoSomeStuffThatPublishesToChannel(my_redis_mock);
25//
26// // Wait for successful detection of Publish call
27// my_redis_mock.Wait();
28//
29// You may want some more complicated checks or behaviours. It such a case, feel
30// free to copy this class and adapt it for your needs.
31class MockPublishWaiter {
32public:
33 // channel_name is used as PREFIX! and not as exact match
34 template <typename T>
35 MockPublishWaiter(
36 GMockClient& redis_mock,
37 const std::string& debug_channel_name,
38 T&& matcher,
39 size_t times_called = 1
40 )
41 : debug_channel_name_(std::move(debug_channel_name))
42 {
43 UINVARIANT(times_called > 0, "times_called must be > 0");
44
45 using ::testing::_;
46 EXPECT_CALL(redis_mock, Publish(std::forward<T>(matcher), _, _, _))
47 .Times(times_called)
48 .WillRepeatedly([this, times_called](auto&& channel, auto&& message, auto&&...) {
49 LOG_DEBUG()
50 << "Redis mock received message to channel: " << channel
51 << "; Called time: " << times_called_.load() + 1;
52 published_messages_.push_back(message);
53 if ((times_called_.fetch_add(1) + 1) == times_called) {
54 on_received_.Send();
55 }
56 });
57 }
58
59 void Wait() {
60 EXPECT_TRUE(on_received_.WaitForEventFor(std::chrono::seconds{30})
61 ) << "Failed to detect publishing to channel "
62 << debug_channel_name_ << " within 30 seconds";
63 }
64
65 const std::string& GetPublishedMessage(size_t index) const { return published_messages_.at(index); }
66 size_t GetPublishedMessagesCount() const { return published_messages_.size(); }
67
68private:
69 engine::SingleConsumerEvent on_received_;
70 std::string debug_channel_name_;
71 std::atomic<size_t> times_called_{0};
72 std::vector<std::string> published_messages_;
73};
74
75} // namespace storages::redis
76
77USERVER_NAMESPACE_END