userver: userver/utest/http_server_mock.hpp Source File
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
http_server_mock.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utest/http_server_mock.hpp
4/// @brief @copybrief utest::HttpServerMock
5
6#include <cstdint>
7#include <map>
8
9#include <userver/utest/simple_server.hpp>
10
11#include <userver/clients/http/request.hpp>
12#include <userver/clients/http/response.hpp>
13
14USERVER_NAMESPACE_BEGIN
15
16namespace utest {
17
18/// @ingroup userver_utest
19///
20/// @brief Toy HTTP server for testing; for raw TCP or TLS testing use utest::SimpleServer.
21///
22/// In constructor opens specified ports in localhost address and listens on
23/// them. On each HTTP request calls user callback.
24///
25/// ## Example usage:
26/// @snippet core/utest/src/utest/http_server_mock_test.cpp Sample HttpServerMock usage
28public:
29 /// Structure with HTTP request that is passed to the HttpHandler callback
30 struct HttpRequest {
31 clients::http::HttpMethod method{clients::http::HttpMethod::kGet};
32 std::string path;
33
34 std::multimap<std::string, std::string> query;
35 clients::http::Headers headers;
36 std::string body;
37 };
38
39 /// Structure with HTTP response to return from the HttpHandler callback
40 struct HttpResponse {
41 int response_status{200};
42 clients::http::Headers headers;
43 std::string body;
44 };
45
46 /// Callback that is invoked on each HTTP request
47 using HttpHandler = std::function<HttpResponse(const HttpRequest&)>;
48
49 HttpServerMock(HttpHandler http_handler, SimpleServer::Protocol protocol = SimpleServer::kTcpIpV4);
50
51 /// Returns URL to the server, for example 'http://127.0.0.1:8080'
52 std::string GetBaseUrl() const;
53
54 std::uint64_t GetConnectionsOpenedCount() const;
55
56private:
57 friend class HttpConnection;
58
59 HttpHandler http_handler_;
60 SimpleServer server_;
61};
62
63} // namespace utest
64
65USERVER_NAMESPACE_END