userver: userver/utest/simple_server.hpp Source File
Loading...
Searching...
No Matches
simple_server.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utest/simple_server.hpp
4/// @brief @copybrief utest::SimpleServer
5
6#include <cstdint>
7#include <functional>
8#include <initializer_list>
9#include <memory>
10#include <string>
11#include <vector>
12
13USERVER_NAMESPACE_BEGIN
14
15namespace utest {
16
17/// @ingroup userver_utest
18///
19/// @brief Toy server for simple network testing; for testing HTTP prefer using utest::HttpServerMock.
20///
21/// In constructor opens specified ports in localhost address and listens on
22/// them. On each accepted data packet calls user callback.
23///
24/// ## Example usage:
25/// @snippet core/src/testing_test.cpp Sample SimpleServer usage
26class SimpleServer final {
27public:
28 /// Response to return from the OnRequest callback
29 struct Response {
30 enum Commands {
31 kWriteAndClose,
32 kTryReadMore,
33 kWriteAndContinue,
34 };
35
36 std::string data_to_send{};
37
38 /// What the SimpleServer has to do with the connection after the `data_to_send` is sent
39 Commands command{kWriteAndClose};
40 };
41
42 /// Request that is passed to the OnRequest callback
43 using Request = std::string;
44
45 /// Callback that is invoked on each network request
46 using OnRequest = std::function<Response(const Request&)>;
47
48 using Port = unsigned short;
49 enum Protocol {
50 kTcpIpV4,
51 kTcpIpV6
52 };
53
54 SimpleServer(OnRequest callback, Protocol protocol = kTcpIpV4);
55 ~SimpleServer();
56
57 /// Returns Port the server listens on.
58 Port GetPort() const;
59
60 enum class Schema {
61 kHttp,
62 kHttps,
63 };
64
65 /// Returns URL to the server, for example 'http://127.0.0.1:8080'
66 std::string GetBaseUrl(Schema type = Schema::kHttp) const;
67
68 std::uint64_t GetConnectionsOpenedCount() const;
69
70private:
71 class Impl;
72 const std::unique_ptr<Impl> pimpl_;
73};
74
75} // namespace utest
76
77USERVER_NAMESPACE_END