blob: 54c6e0c92766dda6b3cbcb84d580d5fdc74c3143 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
#ifndef CEPIS_TESTS_TEST_SERVER_HPP
#define CEPIS_TESTS_TEST_SERVER_HPP
#include <atomic>
#include <functional>
#include <map>
#include <mutex>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
namespace cepis::testing {
/// One canned HTTP response.
struct Reply {
int status = 200;
std::string body;
std::vector<std::pair<std::string, std::string>> headers;
};
/// A throwaway HTTP/1.1 server on a random loopback port.
///
/// The tests point `Config::base_url` at it, so the code path they exercise is
/// the one that runs in production — request construction, header reading and
/// error-body reading included. Nothing is mocked below the socket, and it
/// doubles as the test that `base_url` works: without it none of this runs.
class Server {
public:
Server();
~Server();
Server(const Server&) = delete;
Server& operator=(const Server&) = delete;
Server(Server&&) = delete;
Server& operator=(Server&&) = delete;
/// `http://127.0.0.1:<port>`, ready to hand to `Config::base_url`.
[[nodiscard]] std::string url() const;
/// Registers the response for a path. The last entry of a queue repeats once
/// the earlier ones are consumed, which is how retrying is tested.
void respond(std::string path, Reply reply);
void respond(std::string path, std::vector<Reply> replies);
/// Installs a catch-all that sees every request. Takes precedence over the
/// registered paths.
void handle(std::function<Reply(const std::string& path)> handler);
/// How many requests so far began with `prefix`.
[[nodiscard]] int count(std::string_view prefix) const;
/// Every path requested so far, in order.
[[nodiscard]] std::vector<std::string> calls() const;
private:
void serve();
Reply next(const std::string& path);
int listen_fd_ = -1;
int port_ = 0;
std::atomic<bool> stopping_{false};
std::thread thread_;
mutable std::mutex mutex_;
std::map<std::string, std::vector<Reply>> routes_;
std::function<Reply(const std::string&)> handler_;
std::vector<std::string> calls_;
};
} // namespace cepis::testing
#endif // CEPIS_TESTS_TEST_SERVER_HPP
|