aboutsummaryrefslogtreecommitdiff
path: root/src/zenhttp/asynchttpclient_test.cpp
blob: 1518633705d564b9724c6864b6b7bcf1ef13d03c (plain) (blame)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zenhttp/asynchttpclient.h>
#include <zenhttp/httpserver.h>

#if ZEN_WITH_TESTS

#	include <zencore/iobuffer.h>
#	include <zencore/logging.h>
#	include <zencore/scopeguard.h>
#	include <zencore/testing.h>
#	include <zencore/testutils.h>

#	include "servers/httpasio.h"

#	include <atomic>
#	include <thread>

ZEN_THIRD_PARTY_INCLUDES_START
#	include <asio.hpp>
ZEN_THIRD_PARTY_INCLUDES_END

namespace zen {

using namespace std::literals;

//////////////////////////////////////////////////////////////////////////
// Reusable test service for async client tests

class AsyncHttpClientTestService : public HttpService
{
public:
	AsyncHttpClientTestService()
	{
		m_Router.RegisterRoute(
			"hello",
			[](HttpRouterRequest& Req) { Req.ServerRequest().WriteResponse(HttpResponseCode::OK, HttpContentType::kText, "hello world"); },
			HttpVerb::kGet);

		m_Router.RegisterRoute(
			"echo",
			[](HttpRouterRequest& Req) {
				HttpServerRequest& HttpReq = Req.ServerRequest();
				IoBuffer		   Body	   = HttpReq.ReadPayload();
				HttpContentType	   CT	   = HttpReq.RequestContentType();
				HttpReq.WriteResponse(HttpResponseCode::OK, CT, Body);
			},
			HttpVerb::kPost | HttpVerb::kPut);

		m_Router.RegisterRoute(
			"echo/method",
			[](HttpRouterRequest& Req) {
				HttpServerRequest& HttpReq = Req.ServerRequest();
				std::string_view   Method  = ToString(HttpReq.RequestVerb());
				HttpReq.WriteResponse(HttpResponseCode::OK, HttpContentType::kText, Method);
			},
			HttpVerb::kGet | HttpVerb::kPost | HttpVerb::kPut | HttpVerb::kDelete | HttpVerb::kHead);

		m_Router.RegisterRoute(
			"nocontent",
			[](HttpRouterRequest& Req) { Req.ServerRequest().WriteResponse(HttpResponseCode::NoContent); },
			HttpVerb::kGet | HttpVerb::kPost | HttpVerb::kPut | HttpVerb::kDelete);

		m_Router.RegisterRoute(
			"json",
			[](HttpRouterRequest& Req) {
				Req.ServerRequest().WriteResponse(HttpResponseCode::OK, HttpContentType::kJSON, "{\"ok\":true}");
			},
			HttpVerb::kGet);
	}

	virtual const char* BaseUri() const override { return "/api/async-test/"; }
	virtual void		HandleRequest(HttpServerRequest& Request) override { m_Router.HandleRequest(Request); }

private:
	HttpRequestRouter m_Router;
};

//////////////////////////////////////////////////////////////////////////

struct AsyncTestServerFixture
{
	AsyncHttpClientTestService TestService;
	ScopedTemporaryDirectory   TmpDir;
	Ref<HttpServer>			   Server;
	std::thread				   ServerThread;
	int						   Port = -1;

	AsyncTestServerFixture()
	{
		Server = CreateHttpAsioServer(AsioConfig{});
		Port   = Server->Initialize(0, TmpDir.Path());
		ZEN_ASSERT(Port != -1);
		Server->RegisterService(TestService);
		ServerThread = std::thread([this]() { Server->Run(false); });
	}

	~AsyncTestServerFixture()
	{
		Server->RequestExit();
		if (ServerThread.joinable())
		{
			ServerThread.join();
		}
		Server->Close();
	}

	AsyncHttpClient MakeClient(HttpClientSettings Settings = {}) { return AsyncHttpClient(fmt::format("127.0.0.1:{}", Port), Settings); }

	AsyncHttpClient MakeClient(asio::io_context& IoContext, HttpClientSettings Settings = {})
	{
		return AsyncHttpClient(fmt::format("127.0.0.1:{}", Port), IoContext, Settings);
	}
};

//////////////////////////////////////////////////////////////////////////
// Tests

TEST_SUITE_BEGIN("http.asynchttpclient");

TEST_CASE("asynchttpclient.future.verbs")
{
	AsyncTestServerFixture Fixture;
	AsyncHttpClient		   Client = Fixture.MakeClient();

	SUBCASE("GET returns 200 with expected body")
	{
		auto Future = Client.Get("/api/async-test/echo/method");
		auto Resp	= Future.get();
		CHECK(Resp.IsSuccess());
		CHECK_EQ(Resp.AsText(), "GET");
	}

	SUBCASE("POST dispatches correctly")
	{
		auto Future = Client.Post("/api/async-test/echo/method");
		auto Resp	= Future.get();
		CHECK(Resp.IsSuccess());
		CHECK_EQ(Resp.AsText(), "POST");
	}

	SUBCASE("PUT dispatches correctly")
	{
		auto Future = Client.Put("/api/async-test/echo/method");
		auto Resp	= Future.get();
		CHECK(Resp.IsSuccess());
		CHECK_EQ(Resp.AsText(), "PUT");
	}

	SUBCASE("DELETE dispatches correctly")
	{
		auto Future = Client.Delete("/api/async-test/echo/method");
		auto Resp	= Future.get();
		CHECK(Resp.IsSuccess());
		CHECK_EQ(Resp.AsText(), "DELETE");
	}

	SUBCASE("HEAD returns 200 with empty body")
	{
		auto Future = Client.Head("/api/async-test/echo/method");
		auto Resp	= Future.get();
		CHECK(Resp.IsSuccess());
		CHECK_EQ(Resp.AsText(), ""sv);
	}
}

TEST_CASE("asynchttpclient.future.get")
{
	AsyncTestServerFixture Fixture;
	AsyncHttpClient		   Client = Fixture.MakeClient();

	SUBCASE("simple GET with text response")
	{
		auto Future = Client.Get("/api/async-test/hello");
		auto Resp	= Future.get();
		CHECK(Resp.IsSuccess());
		CHECK_EQ(Resp.StatusCode, HttpResponseCode::OK);
		CHECK_EQ(Resp.AsText(), "hello world");
	}

	SUBCASE("GET returning JSON")
	{
		auto Future = Client.Get("/api/async-test/json");
		auto Resp	= Future.get();
		CHECK(Resp.IsSuccess());
		CHECK_EQ(Resp.AsText(), "{\"ok\":true}");
	}

	SUBCASE("GET 204 NoContent")
	{
		auto Future = Client.Get("/api/async-test/nocontent");
		auto Resp	= Future.get();
		CHECK(Resp.IsSuccess());
		CHECK_EQ(Resp.StatusCode, HttpResponseCode::NoContent);
	}
}

TEST_CASE("asynchttpclient.future.post.with.payload")
{
	AsyncTestServerFixture Fixture;
	AsyncHttpClient		   Client = Fixture.MakeClient();

	std::string_view PayloadStr = "async payload data";
	IoBuffer		 Payload(IoBuffer::Clone, PayloadStr.data(), PayloadStr.size());
	Payload.SetContentType(ZenContentType::kText);

	auto Future = Client.Post("/api/async-test/echo", Payload);
	auto Resp	= Future.get();
	CHECK(Resp.IsSuccess());
	CHECK_EQ(Resp.AsText(), "async payload data");
}

TEST_CASE("asynchttpclient.future.put.with.payload")
{
	AsyncTestServerFixture Fixture;
	AsyncHttpClient		   Client = Fixture.MakeClient();

	std::string_view PutStr = "put payload";
	IoBuffer		 Payload(IoBuffer::Clone, PutStr.data(), PutStr.size());
	Payload.SetContentType(ZenContentType::kText);

	auto Future = Client.Put("/api/async-test/echo", Payload);
	auto Resp	= Future.get();
	CHECK(Resp.IsSuccess());
	CHECK_EQ(Resp.AsText(), "put payload");
}

TEST_CASE("asynchttpclient.callback")
{
	AsyncTestServerFixture Fixture;
	AsyncHttpClient		   Client = Fixture.MakeClient();

	std::promise<HttpClient::Response> Promise;
	auto							   Future = Promise.get_future();

	Client.AsyncGet("/api/async-test/hello", [&Promise](HttpClient::Response Resp) { Promise.set_value(std::move(Resp)); });

	auto Resp = Future.get();
	CHECK(Resp.IsSuccess());
	CHECK_EQ(Resp.AsText(), "hello world");
}

TEST_CASE("asynchttpclient.concurrent.requests")
{
	AsyncTestServerFixture Fixture;
	AsyncHttpClient		   Client = Fixture.MakeClient();

	// Fire multiple requests concurrently
	auto Future1 = Client.Get("/api/async-test/hello");
	auto Future2 = Client.Get("/api/async-test/json");
	auto Future3 = Client.Post("/api/async-test/echo/method");
	auto Future4 = Client.Delete("/api/async-test/echo/method");

	auto Resp1 = Future1.get();
	auto Resp2 = Future2.get();
	auto Resp3 = Future3.get();
	auto Resp4 = Future4.get();

	CHECK(Resp1.IsSuccess());
	CHECK_EQ(Resp1.AsText(), "hello world");

	CHECK(Resp2.IsSuccess());
	CHECK_EQ(Resp2.AsText(), "{\"ok\":true}");

	CHECK(Resp3.IsSuccess());
	CHECK_EQ(Resp3.AsText(), "POST");

	CHECK(Resp4.IsSuccess());
	CHECK_EQ(Resp4.AsText(), "DELETE");
}

TEST_CASE("asynchttpclient.external.io_context")
{
	AsyncTestServerFixture Fixture;

	asio::io_context IoContext;
	auto			 WorkGuard = asio::make_work_guard(IoContext);
	std::thread		 IoThread([&IoContext]() { IoContext.run(); });

	{
		AsyncHttpClient Client = Fixture.MakeClient(IoContext);

		auto Future = Client.Get("/api/async-test/hello");
		auto Resp	= Future.get();
		CHECK(Resp.IsSuccess());
		CHECK_EQ(Resp.AsText(), "hello world");
	}

	WorkGuard.reset();
	IoThread.join();
}

TEST_CASE("asynchttpclient.connection.error")
{
	// Connect to a port where nothing is listening
	AsyncHttpClient Client("127.0.0.1:1", HttpClientSettings{.ConnectTimeout = std::chrono::milliseconds(500)});

	auto Future = Client.Get("/should-fail");
	auto Resp	= Future.get();

	CHECK_FALSE(Resp.IsSuccess());
	CHECK(Resp.Error.has_value());
	CHECK(Resp.Error->IsConnectionError());
}

TEST_SUITE_END();

void
asynchttpclient_test_forcelink()
{
}

}  // namespace zen

#endif