userver: userver/utest/simple_server.hpp Source File
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
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 { kTcpIpV4, kTcpIpV6 };
50
51 SimpleServer(OnRequest callback, Protocol protocol = kTcpIpV4);
52 ~SimpleServer();
53
54 /// Returns Port the server listens on.
55 Port GetPort() const;
56
57 enum class Schema {
58 kHttp,
59 kHttps,
60 };
61
62 /// Returns URL to the server, for example 'http://127.0.0.1:8080'
63 std::string GetBaseUrl(Schema type = Schema::kHttp) const;
64
65 std::uint64_t GetConnectionsOpenedCount() const;
66
67private:
68 class Impl;
69 const std::unique_ptr<Impl> pimpl_;
70};
71
72} // namespace utest
73
74USERVER_NAMESPACE_END