Github User Fetcher 1.0.0
C Application with Server and GUI
Loading...
Searching...
No Matches
test_server.cpp
Go to the documentation of this file.
1#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
2#include "server.hpp"
3#include <boost/asio.hpp>
4#include <boost/beast/core.hpp>
5#include <boost/beast/http.hpp>
6#include <chrono>
7#include <doctest.h>
8#include <thread>
9
10namespace beast = boost::beast;
11namespace http = beast::http;
12namespace net = boost::asio;
13using tcp = net::ip::tcp;
14
15TEST_CASE("HTTP server responds with GitHub user") {
16 const int test_port = 8123;
17 std::thread server_thread([&]() {
18 start_http_server(test_port); // will block
19 });
20 std::this_thread::sleep_for(
21 std::chrono::seconds(2)); // wait for server to start
22
23 net::io_context ioc;
24 tcp::resolver resolver(ioc);
25 auto const results = resolver.resolve("127.0.0.1", std::to_string(test_port));
26 beast::tcp_stream stream(ioc);
27 stream.connect(results);
28
29 http::request<http::string_body> req(http::verb::get, "/octocat", 11);
30 req.set(http::field::host, "127.0.0.1");
31 req.set(http::field::user_agent, "test-client");
32 http::write(stream, req);
33
34 beast::flat_buffer buffer;
35 http::response<http::string_body> res;
36 http::read(stream, buffer, res);
37
38 CHECK(res.result() == http::status::ok);
39 CHECK(res.body().find("octocat") != std::string::npos);
40
41 beast::error_code ec;
42 stream.socket().shutdown(tcp::socket::shutdown_both, ec);
43
44 // Kill server (not ideal, better to make server stop externally)
45 std::raise(SIGINT);
46 server_thread.join();
47}
#define CHECK(...)
Definition doctest.h:2970
#define TEST_CASE(name)
Definition doctest.h:2937
void start_http_server(int port)
Starts an HTTP server on the specified port.
Definition server.c:59
net::ip::tcp tcp
Definition server.cpp:26