|
5 | 5 | #ifndef BITCOIN_TEST_UTIL_NET_H
|
6 | 6 | #define BITCOIN_TEST_UTIL_NET_H
|
7 | 7 |
|
| 8 | +#include <compat.h> |
8 | 9 | #include <net.h>
|
| 10 | +#include <util/sock.h> |
| 11 | + |
| 12 | +#include <cassert> |
| 13 | +#include <cstring> |
| 14 | +#include <string> |
9 | 15 |
|
10 | 16 | struct ConnmanTestMsg : public CConnman {
|
11 | 17 | using CConnman::CConnman;
|
@@ -61,4 +67,67 @@ constexpr ConnectionType ALL_CONNECTION_TYPES[]{
|
61 | 67 | ConnectionType::ADDR_FETCH,
|
62 | 68 | };
|
63 | 69 |
|
| 70 | +/** |
| 71 | + * A mocked Sock alternative that returns a statically contained data upon read and succeeds |
| 72 | + * and ignores all writes. The data to be returned is given to the constructor and when it is |
| 73 | + * exhausted an EOF is returned by further reads. |
| 74 | + */ |
| 75 | +class StaticContentsSock : public Sock |
| 76 | +{ |
| 77 | +public: |
| 78 | + explicit StaticContentsSock(const std::string& contents) : m_contents{contents}, m_consumed{0} |
| 79 | + { |
| 80 | + // Just a dummy number that is not INVALID_SOCKET. |
| 81 | + static_assert(INVALID_SOCKET != 1000); |
| 82 | + m_socket = 1000; |
| 83 | + } |
| 84 | + |
| 85 | + ~StaticContentsSock() override { Reset(); } |
| 86 | + |
| 87 | + StaticContentsSock& operator=(Sock&& other) override |
| 88 | + { |
| 89 | + assert(false && "Move of Sock into MockSock not allowed."); |
| 90 | + return *this; |
| 91 | + } |
| 92 | + |
| 93 | + void Reset() override |
| 94 | + { |
| 95 | + m_socket = INVALID_SOCKET; |
| 96 | + } |
| 97 | + |
| 98 | + ssize_t Send(const void*, size_t len, int) const override { return len; } |
| 99 | + |
| 100 | + ssize_t Recv(void* buf, size_t len, int flags) const override |
| 101 | + { |
| 102 | + const size_t consume_bytes{std::min(len, m_contents.size() - m_consumed)}; |
| 103 | + std::memcpy(buf, m_contents.data() + m_consumed, consume_bytes); |
| 104 | + if ((flags & MSG_PEEK) == 0) { |
| 105 | + m_consumed += consume_bytes; |
| 106 | + } |
| 107 | + return consume_bytes; |
| 108 | + } |
| 109 | + |
| 110 | + int Connect(const sockaddr*, socklen_t) const override { return 0; } |
| 111 | + |
| 112 | + int GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const override |
| 113 | + { |
| 114 | + std::memset(opt_val, 0x0, *opt_len); |
| 115 | + return 0; |
| 116 | + } |
| 117 | + |
| 118 | + bool Wait(std::chrono::milliseconds timeout, |
| 119 | + Event requested, |
| 120 | + Event* occurred = nullptr) const override |
| 121 | + { |
| 122 | + if (occurred != nullptr) { |
| 123 | + *occurred = requested; |
| 124 | + } |
| 125 | + return true; |
| 126 | + } |
| 127 | + |
| 128 | +private: |
| 129 | + const std::string m_contents; |
| 130 | + mutable size_t m_consumed; |
| 131 | +}; |
| 132 | + |
64 | 133 | #endif // BITCOIN_TEST_UTIL_NET_H
|
0 commit comments