diff --git a/blocks/html/html.h b/blocks/html/html.h
index a3e3bba17..69a43ff5a 100644
--- a/blocks/html/html.h
+++ b/blocks/html/html.h
@@ -150,7 +150,7 @@ struct HTMLGeneratorOStreamScope final : HTMLGeneratorScope {
#define CURRENT_HTML_SWITCH(x, y) x y
#define HTML(...) CURRENT_HTML_SWITCH(CURRENT_HTML_SWITCH_N(CURRENT_HTML_NARGS(__VA_ARGS__)), (__VA_ARGS__))
-} // namespace current::html
+} // namespace html
} // namespace current
// The `htmltag` namespace is intentionally in the global scope, not within `::current`, so that it can be amended to.
@@ -168,7 +168,7 @@ struct _ final {
}
};
-} // namespace ::htmltag
+} // namespace htmltag
#include "tags.h"
diff --git a/blocks/html/html_http.h b/blocks/html/html_http.h
index cc04b91c5..0979b05ac 100644
--- a/blocks/html/html_http.h
+++ b/blocks/html/html_http.h
@@ -52,7 +52,7 @@ struct HTMLGeneratorHTTPResponseScope final : HTMLGeneratorScope {
std::ostream& OutputStream() override { return html_contents; }
};
-} // namespace current::html
+} // namespace html
} // namespace current
#endif // BLOCKS_HTML_HTTP_H
diff --git a/blocks/html/tags.h b/blocks/html/tags.h
index 89c46efe0..996ebcca3 100644
--- a/blocks/html/tags.h
+++ b/blocks/html/tags.h
@@ -78,7 +78,6 @@ namespace htmltag {
#define CURRENT_HTML_TAG(...) \
CURRENT_HTML_TAG_SWITCH(CURRENT_HTML_TAG_SWITCH_N(CURRENT_HTML_TAG_NARGS(__VA_ARGS__)), (__VA_ARGS__))
-
// clang-format off
#define CURRENT_HTML_START_ONLY_TAG_COUNT_3(tag, param1, param2) \
@@ -148,6 +147,6 @@ CURRENT_HTML_TAG(table, border, cellpadding);
CURRENT_HTML_TAG(tr);
CURRENT_HTML_TAG(td, align, colspan, valign);
-} // namespace ::htmltag
+} // namespace htmltag
#endif // BLOCKS_HTML_TAGS_H
diff --git a/blocks/html/test.cc b/blocks/html/test.cc
index ee707598a..5865c5438 100644
--- a/blocks/html/test.cc
+++ b/blocks/html/test.cc
@@ -141,7 +141,7 @@ TEST(HTMLTest, Smoke) {
{
const auto scope = current::html::HTMLGeneratorOStreamScope(oss);
HTML(table, border(0)); // Number, not a string.
- }
+ }
EXPECT_EQ("
", oss.str());
}
{
@@ -149,7 +149,7 @@ TEST(HTMLTest, Smoke) {
{
const auto scope = current::html::HTMLGeneratorOStreamScope(oss);
HTML(input, value(42)); // Number, not a string.
- }
+ }
EXPECT_EQ("", oss.str());
}
}
diff --git a/blocks/http/api.h b/blocks/http/api.h
index cb64583e3..14509a71a 100644
--- a/blocks/http/api.h
+++ b/blocks/http/api.h
@@ -78,8 +78,8 @@ inline typename current::weed::call_with_type HTTP(TS&&... par
using current::http::HTTP;
using current::http::Request;
-using current::http::Response;
using current::http::ReRegisterRoute;
+using current::http::Response;
using HTTPRoutesScope = typename HTTP_IMPL::server_impl_t::HTTPRoutesScope;
using HTTPRoutesScopeEntry = current::http::HTTPServerPOSIX::HTTPRoutesScopeEntry;
diff --git a/blocks/http/chunked_demo.cc b/blocks/http/chunked_demo.cc
index ce5c159f0..108dc5b74 100644
--- a/blocks/http/chunked_demo.cc
+++ b/blocks/http/chunked_demo.cc
@@ -105,9 +105,9 @@ y:0.183947}
#include "../../bricks/strings/printf.h"
#include "../../bricks/time/chrono.h"
-using current::time::Now;
-using current::strings::Printf;
using current::net::http::Headers;
+using current::strings::Printf;
+using current::time::Now;
DEFINE_int32(port, 8181, "The port to serve chunked response on.");
@@ -150,58 +150,55 @@ CURRENT_STRUCT(ExampleMeta) {
// TODO(dkorolev): Finish multithreading. Need to notify active connections and wait for them to finish.
int main() {
- HTTP(FLAGS_port)
- .Register("/layout",
- [](Request r) {
- LayoutItem layout;
- LayoutItem row;
- layout.col.push_back(row);
- r(layout,
- // "layout", <-- @dkorolev, remove this source file entirely, as it's obsolete.
- HTTPResponseCode.OK,
- Headers({{"Connection", "close"}, {"Access-Control-Allow-Origin", "*"}}),
- "application/json; charset=utf-8");
- });
- HTTP(FLAGS_port)
- .Register("/meta",
- [](Request r) {
- r(ExampleMeta(),
- // "meta", <-- @dkorolev, remove this source file entirely, as it's obsolete.
- HTTPResponseCode.OK,
- Headers({{"Connection", "close"}, {"Access-Control-Allow-Origin", "*"}}),
- "application/json; charset=utf-8");
- });
- HTTP(FLAGS_port)
- .Register("/data",
- [](Request r) {
- std::thread([](Request&& r) {
- // Since we are in another thread, need to catch exceptions ourselves.
- try {
- auto response = r.connection.SendChunkedHTTPResponse(
- HTTPResponseCode.OK,
- {{"Connection", "keep-alive"}, {"Access-Control-Allow-Origin", "*"}},
- "application/json; charset=utf-8");
- std::string data;
- const double begin = static_cast(Now().count());
- const double t = atof(r.url.query["t"].c_str());
- const double end = (t > 0) ? (begin + t * 1e3) : 1e18;
- double current;
- while ((current = static_cast(Now().count())) < end) {
- std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100 + 100));
- const double x = current;
- const double y = sin(5e-3 * (current - begin));
- data += Printf("{\"x\":%lf,\"y\":%lf}\n", x, y);
- const double f = (rand() % 101) * (rand() % 101) * (rand() % 101) * 1e-6;
- const size_t n = static_cast(data.length() * f);
- if (n) {
- response.Send(data.substr(0, n));
- data = data.substr(n);
- }
- }
- } catch (const current::Exception& e) {
- std::cerr << "Exception in data serving thread: " << e.what() << std::endl;
- }
- }, std::move(r)).detach();
- });
+ HTTP(FLAGS_port).Register("/layout", [](Request r) {
+ LayoutItem layout;
+ LayoutItem row;
+ layout.col.push_back(row);
+ r(layout,
+ // "layout", <-- @dkorolev, remove this source file entirely, as it's obsolete.
+ HTTPResponseCode.OK,
+ Headers({{"Connection", "close"}, {"Access-Control-Allow-Origin", "*"}}),
+ "application/json; charset=utf-8");
+ });
+ HTTP(FLAGS_port).Register("/meta", [](Request r) {
+ r(ExampleMeta(),
+ // "meta", <-- @dkorolev, remove this source file entirely, as it's obsolete.
+ HTTPResponseCode.OK,
+ Headers({{"Connection", "close"}, {"Access-Control-Allow-Origin", "*"}}),
+ "application/json; charset=utf-8");
+ });
+ HTTP(FLAGS_port).Register("/data", [](Request r) {
+ std::thread(
+ [](Request&& r) {
+ // Since we are in another thread, need to catch exceptions ourselves.
+ try {
+ auto response = r.connection.SendChunkedHTTPResponse(
+ HTTPResponseCode.OK,
+ {{"Connection", "keep-alive"}, {"Access-Control-Allow-Origin", "*"}},
+ "application/json; charset=utf-8");
+ std::string data;
+ const double begin = static_cast(Now().count());
+ const double t = atof(r.url.query["t"].c_str());
+ const double end = (t > 0) ? (begin + t * 1e3) : 1e18;
+ double current;
+ while ((current = static_cast(Now().count())) < end) {
+ std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100 + 100));
+ const double x = current;
+ const double y = sin(5e-3 * (current - begin));
+ data += Printf("{\"x\":%lf,\"y\":%lf}\n", x, y);
+ const double f = (rand() % 101) * (rand() % 101) * (rand() % 101) * 1e-6;
+ const size_t n = static_cast(data.length() * f);
+ if (n) {
+ response.Send(data.substr(0, n));
+ data = data.substr(n);
+ }
+ }
+ } catch (const current::Exception& e) {
+ std::cerr << "Exception in data serving thread: " << e.what() << std::endl;
+ }
+ },
+ std::move(r))
+ .detach();
+ });
HTTP(FLAGS_port).Join();
}
diff --git a/blocks/http/impl/posix_client.h b/blocks/http/impl/posix_client.h
index b686744b4..9cf8c8573 100644
--- a/blocks/http/impl/posix_client.h
+++ b/blocks/http/impl/posix_client.h
@@ -57,7 +57,7 @@ struct HTTPRedirectHelper : current::net::HTTPDefaultHelper {
current::net::HTTPDefaultHelper::OnHeader(key, value);
}
};
-} // namespace current::http::impl
+} // namespace impl
template
class GenericHTTPClientPOSIX final {
@@ -94,8 +94,7 @@ class GenericHTTPClientPOSIX final {
port = 80;
}
}
- current::net::Connection connection(
- current::net::Connection(current::net::ClientSocket(parsed_url.host, port)));
+ current::net::Connection connection(current::net::Connection(current::net::ClientSocket(parsed_url.host, port)));
connection.BlockingWrite(
request_method_ + ' ' + parsed_url.path + parsed_url.ComposeParameters() + " HTTP/1.1\r\n", true);
connection.BlockingWrite("Host: " + parsed_url.host + "\r\n", true);
diff --git a/blocks/http/impl/posix_server.h b/blocks/http/impl/posix_server.h
index c98e917f2..e57ee877c 100644
--- a/blocks/http/impl/posix_server.h
+++ b/blocks/http/impl/posix_server.h
@@ -163,7 +163,9 @@ class HTTPServerPOSIX final {
// Since instances of `HTTPServerPOSIX` are created via a singleton,
// a listening thread will only be created once per port, on the first access to that port.
explicit HTTPServerPOSIX(current::net::BarePort port)
- : terminating_(false), port_(static_cast(port)), thread_([this, port]() { Thread(current::net::Socket(port)); }) {}
+ : terminating_(false),
+ port_(static_cast(port)),
+ thread_([this, port]() { Thread(current::net::Socket(port)); }) {}
explicit HTTPServerPOSIX(current::net::ReservedLocalPort reserved_port)
: terminating_(false),
port_(reserved_port),
@@ -223,7 +225,8 @@ class HTTPServerPOSIX final {
const URLPathArgs::CountMask path_args_count_mask,
F& handler) {
std::lock_guard lock(mutex_);
- return DoRegisterHandler(path, [&handler](Request r) { handler(std::move(r)); }, path_args_count_mask, POLICY);
+ return DoRegisterHandler(
+ path, [&handler](Request r) { handler(std::move(r)); }, path_args_count_mask, POLICY);
}
template
diff --git a/blocks/http/test.cc b/blocks/http/test.cc
index aebbd03cc..a9d643746 100644
--- a/blocks/http/test.cc
+++ b/blocks/http/test.cc
@@ -52,21 +52,21 @@ SOFTWARE.
using std::string;
-using current::strings::Printf;
-using current::Singleton;
-using current::FileSystem;
using current::FileException;
+using current::FileSystem;
+using current::Singleton;
+using current::strings::Printf;
using current::net::Connection;
using current::net::HTTPResponseCodeValue;
using current::net::http::Headers;
using current::net::DefaultInternalServerErrorMessage;
-using current::net::DefaultNotFoundMessage;
using current::net::DefaultMethodNotAllowedMessage;
+using current::net::DefaultNotFoundMessage;
-using current::net::HTTPRedirectNotAllowedException;
using current::net::HTTPRedirectLoopException;
+using current::net::HTTPRedirectNotAllowedException;
using current::net::SocketResolveAddressException;
DEFINE_string(net_api_test_tmpdir, ".current", "Local path for the test to create temporary files in.");
@@ -126,16 +126,13 @@ TEST(HTTPAPI, RegisterWithURLPathParams) {
};
const auto scope = HTTP(port).Register("/", URLPathArgs::CountMask::Any, handler) +
- HTTP(port)
- .Register("/user", URLPathArgs::CountMask::One | URLPathArgs::CountMask::Two, handler) +
+ HTTP(port).Register("/user", URLPathArgs::CountMask::One | URLPathArgs::CountMask::Two, handler) +
HTTP(port).Register("/user/a", URLPathArgs::CountMask::One, handler) +
HTTP(port).Register("/user/a/1", URLPathArgs::CountMask::None, handler);
ASSERT_THROW(HTTP(port).Register("/", handler), HandlerAlreadyExistsException);
- ASSERT_THROW(HTTP(port).Register("/user", URLPathArgs::CountMask::Two, handler),
- HandlerAlreadyExistsException);
- ASSERT_THROW(HTTP(port).Register("/user/a", URLPathArgs::CountMask::One, handler),
- HandlerAlreadyExistsException);
+ ASSERT_THROW(HTTP(port).Register("/user", URLPathArgs::CountMask::Two, handler), HandlerAlreadyExistsException);
+ ASSERT_THROW(HTTP(port).Register("/user/a", URLPathArgs::CountMask::One, handler), HandlerAlreadyExistsException);
ASSERT_THROW(HTTP(port).Register("/user/a/1", handler), HandlerAlreadyExistsException);
const auto run = [port](const std::string& path) -> std::string {
@@ -299,14 +296,10 @@ TEST(HTTPAPI, URLParameters) {
const auto scope = http_server.Register("/query", [](Request r) { r("x=" + r.url.query["x"]); });
EXPECT_EQ("x=", HTTP(GET(Printf("http://localhost:%d/query", port))).body);
EXPECT_EQ("x=42", HTTP(GET(Printf("http://localhost:%d/query?x=42", port))).body);
- EXPECT_EQ("x=test passed",
- HTTP(GET(Printf("http://localhost:%d/query?x=test+passed", port))).body);
- EXPECT_EQ("x=test passed",
- HTTP(GET(Printf("http://localhost:%d/query?x=test%%20passed", port))).body);
- EXPECT_EQ("x=test/passed",
- HTTP(GET(Printf("http://localhost:%d/query?x=test%%2fpassed", port))).body);
- EXPECT_EQ("x=test/passed",
- HTTP(GET(Printf("http://localhost:%d/query?x=test%%2Fpassed", port))).body);
+ EXPECT_EQ("x=test passed", HTTP(GET(Printf("http://localhost:%d/query?x=test+passed", port))).body);
+ EXPECT_EQ("x=test passed", HTTP(GET(Printf("http://localhost:%d/query?x=test%%20passed", port))).body);
+ EXPECT_EQ("x=test/passed", HTTP(GET(Printf("http://localhost:%d/query?x=test%%2fpassed", port))).body);
+ EXPECT_EQ("x=test/passed", HTTP(GET(Printf("http://localhost:%d/query?x=test%%2Fpassed", port))).body);
}
TEST(HTTPAPI, InvalidHEXInURLParameters) {
@@ -339,21 +332,19 @@ TEST(HTTPAPI, HeadersAndCookies) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/headers_and_cookies",
- [](Request r) {
- EXPECT_TRUE(r.headers.Has("Header1"));
- EXPECT_TRUE(r.headers.Has("Header2"));
- EXPECT_EQ("foo", r.headers["Header1"].value);
- EXPECT_EQ("bar", r.headers["Header2"].value);
- EXPECT_EQ("x=1; y=2", r.headers.CookiesAsString());
- Response response("OK");
- response.headers.Set("X-Current-H1", "header1");
- response.SetCookie("cookie1", "value1");
- response.headers.Set("X-Current-H2", "header2");
- response.SetCookie("cookie2", "value2");
- r(response);
- });
+ const auto scope = http_server.Register("/headers_and_cookies", [](Request r) {
+ EXPECT_TRUE(r.headers.Has("Header1"));
+ EXPECT_TRUE(r.headers.Has("Header2"));
+ EXPECT_EQ("foo", r.headers["Header1"].value);
+ EXPECT_EQ("bar", r.headers["Header2"].value);
+ EXPECT_EQ("x=1; y=2", r.headers.CookiesAsString());
+ Response response("OK");
+ response.headers.Set("X-Current-H1", "header1");
+ response.SetCookie("cookie1", "value1");
+ response.headers.Set("X-Current-H2", "header2");
+ response.SetCookie("cookie2", "value2");
+ r(response);
+ });
const auto response = HTTP(GET(Printf("http://localhost:%d/headers_and_cookies", port))
.SetHeader("Header1", "foo")
.SetCookie("x", "1")
@@ -372,16 +363,14 @@ TEST(HTTPAPI, ConnectionIPAndPort) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/foo",
- [port](Request r) {
- const auto& c = r.connection;
- EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip);
- EXPECT_EQ(port, c.LocalIPAndPort().port);
- EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip);
- EXPECT_LT(0, c.RemoteIPAndPort().port);
- r("bar", HTTPResponseCode.OK);
- });
+ const auto scope = http_server.Register("/foo", [port](Request r) {
+ const auto& c = r.connection;
+ EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip);
+ EXPECT_EQ(port, c.LocalIPAndPort().port);
+ EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip);
+ EXPECT_LT(0, c.RemoteIPAndPort().port);
+ r("bar", HTTPResponseCode.OK);
+ });
const string url = Printf("http://localhost:%d/foo", port);
const auto response = HTTP(GET(url));
EXPECT_EQ(200, static_cast(response.code));
@@ -395,12 +384,9 @@ TEST(HTTPAPI, RespondsWithString) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope =
- http_server
- .Register("/responds_with_string",
- [](Request r) {
- r("test_string", HTTPResponseCode.OK, Headers({{"foo", "bar"}}), "application/json");
- });
+ const auto scope = http_server.Register("/responds_with_string", [](Request r) {
+ r("test_string", HTTPResponseCode.OK, Headers({{"foo", "bar"}}), "application/json");
+ });
const string url = Printf("http://localhost:%d/responds_with_string", port);
const auto response = HTTP(GET(url));
EXPECT_EQ(200, static_cast(response.code));
@@ -415,14 +401,9 @@ TEST(HTTPAPI, RespondsWithObject) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/responds_with_object",
- [](Request r) {
- r(HTTPAPITestObject(),
- HTTPResponseCode.OK,
- Headers({{"foo", "bar"}}),
- "application/json");
- });
+ const auto scope = http_server.Register("/responds_with_object", [](Request r) {
+ r(HTTPAPITestObject(), HTTPResponseCode.OK, Headers({{"foo", "bar"}}), "application/json");
+ });
const string url = Printf("http://localhost:%d/responds_with_object", port);
const auto response = HTTP(GET(url));
EXPECT_EQ(200, static_cast(response.code));
@@ -456,12 +437,10 @@ TEST(HTTPAPI, HandlesRespondTwiceWithString) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/respond_twice",
- [](Request r) {
- r("OK");
- r("FAIL");
- });
+ const auto scope = http_server.Register("/respond_twice", [](Request r) {
+ r("OK");
+ r("FAIL");
+ });
const string url = Printf("http://localhost:%d/respond_twice", port);
const auto response = HTTP(GET(url));
EXPECT_EQ(200, static_cast(response.code));
@@ -476,19 +455,17 @@ TEST(HTTPAPI, HandlesRespondTwiceWithResponse) {
std::string result = "";
std::atomic_bool result_ready(false);
- const auto scope = http_server
- .Register("/respond_twice",
- [&result, &result_ready](Request r) {
- r(Response("OK", HTTPResponseCode.OK));
- try {
- r(Response("FAIL", HTTPResponseCode(762)));
- result = "Error, second response did not throw.";
- result_ready = true;
- } catch (const current::net::AttemptedToSendHTTPResponseMoreThanOnce&) {
- result = "OK, second response did throw.";
- result_ready = true;
- }
- });
+ const auto scope = http_server.Register("/respond_twice", [&result, &result_ready](Request r) {
+ r(Response("OK", HTTPResponseCode.OK));
+ try {
+ r(Response("FAIL", HTTPResponseCode(762)));
+ result = "Error, second response did not throw.";
+ result_ready = true;
+ } catch (const current::net::AttemptedToSendHTTPResponseMoreThanOnce&) {
+ result = "OK, second response did throw.";
+ result_ready = true;
+ }
+ });
const string url = Printf("http://localhost:%d/respond_twice", port);
const auto response = HTTP(GET(url));
EXPECT_EQ(200, static_cast(response.code));
@@ -508,26 +485,16 @@ TEST(HTTPAPI, RedirectToRelativeURL) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/from",
- [](Request r) {
- r("",
- HTTPResponseCode.Found,
- Headers({{"Location", "/to"}}),
- current::net::constants::kDefaultHTMLContentType);
- }) +
- http_server.Register("/to", [](Request r) { r("Done."); });
+ const auto scope = http_server.Register("/from", [](Request r) {
+ r("", HTTPResponseCode.Found, Headers({{"Location", "/to"}}), current::net::constants::kDefaultHTMLContentType);
+ }) + http_server.Register("/to", [](Request r) { r("Done."); });
// Redirect not allowed by default.
ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/from", port))), HTTPRedirectNotAllowedException);
// Redirect allowed when `.AllowRedirects()` is set.
const auto response = HTTP(GET(Printf("http://localhost:%d/from", port)).AllowRedirects());
EXPECT_EQ(200, static_cast(response.code));
EXPECT_EQ("Done.", response.body);
- EXPECT_EQ((
- port == 80
- ? "http://localhost/to"
- : Printf("http://localhost:%d/to", port)
- ), response.url);
+ EXPECT_EQ((port == 80 ? "http://localhost/to" : Printf("http://localhost:%d/to", port)), response.url);
}
TEST(HTTPAPI, RedirectToFullURL) {
@@ -541,15 +508,12 @@ TEST(HTTPAPI, RedirectToFullURL) {
// Need a live port for the redirect target because the HTTP client is following the redirect
// and tries to connect to the redirect target, otherwise throws a `SocketConnectException`.
const auto scope_redirect_to = HTTP(std::move(second_reserved_port)).Register("/to", [](Request r) { r("Done."); });
- const auto scope =
- http_server
- .Register("/from",
- [second_port](Request r) {
- r("",
- HTTPResponseCode.Found,
- Headers({{"Location", Printf("http://localhost:%d/to", second_port)}}),
- current::net::constants::kDefaultHTMLContentType);
- });
+ const auto scope = http_server.Register("/from", [second_port](Request r) {
+ r("",
+ HTTPResponseCode.Found,
+ Headers({{"Location", Printf("http://localhost:%d/to", second_port)}}),
+ current::net::constants::kDefaultHTMLContentType);
+ });
// Redirect not allowed by default.
ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/from", port))), HTTPRedirectNotAllowedException);
// Redirect allowed when `.AllowRedirects()` is set.
@@ -593,30 +557,13 @@ TEST(HTTPAPI, RedirectLoop) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/p1",
- [](Request r) {
- r("",
- HTTPResponseCode.Found,
- Headers({{"Location", "/p2"}}),
- current::net::constants::kDefaultHTMLContentType);
- }) +
- http_server
- .Register("/p2",
- [](Request r) {
- r("",
- HTTPResponseCode.Found,
- Headers({{"Location", "/p3"}}),
- current::net::constants::kDefaultHTMLContentType);
- }) +
- http_server
- .Register("/p3",
- [](Request r) {
- r("",
- HTTPResponseCode.Found,
- Headers({{"Location", "/p1"}}),
- current::net::constants::kDefaultHTMLContentType);
- });
+ const auto scope = http_server.Register("/p1", [](Request r) {
+ r("", HTTPResponseCode.Found, Headers({{"Location", "/p2"}}), current::net::constants::kDefaultHTMLContentType);
+ }) + http_server.Register("/p2", [](Request r) {
+ r("", HTTPResponseCode.Found, Headers({{"Location", "/p3"}}), current::net::constants::kDefaultHTMLContentType);
+ }) + http_server.Register("/p3", [](Request r) {
+ r("", HTTPResponseCode.Found, Headers({{"Location", "/p1"}}), current::net::constants::kDefaultHTMLContentType);
+ });
{
bool thrown = false;
try {
@@ -647,11 +594,9 @@ TEST(HTTPAPI, ResponseDotNotation) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/response_dot_notation",
- [](Request r) {
- r(Response("OK").Code(HTTPResponseCode.Created).SetHeader("X-Foo", "bar"));
- });
+ const auto scope = http_server.Register("/response_dot_notation", [](Request r) {
+ r(Response("OK").Code(HTTPResponseCode.Created).SetHeader("X-Foo", "bar"));
+ });
const auto response = HTTP(GET(Printf("http://localhost:%d/response_dot_notation", port)));
EXPECT_EQ("OK", response.body);
EXPECT_EQ(201, static_cast(response.code));
@@ -659,22 +604,15 @@ TEST(HTTPAPI, ResponseDotNotation) {
EXPECT_EQ("bar", response.headers.Get("X-Foo"));
}
-static Response BuildResponse() {
- return Response("").Code(HTTPResponseCode.NoContent).SetHeader("X-Meh", "foo");
-}
+static Response BuildResponse() { return Response("").Code(HTTPResponseCode.NoContent).SetHeader("X-Meh", "foo"); }
TEST(HTTPAPI, ResponseDotNotationReturnedFromAFunction) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/response_returned_from_function",
- [](Request r) {
- r(BuildResponse());
- });
- const auto response =
- HTTP(GET(Printf("http://localhost:%d/response_returned_from_function", port)));
+ const auto scope = http_server.Register("/response_returned_from_function", [](Request r) { r(BuildResponse()); });
+ const auto response = HTTP(GET(Printf("http://localhost:%d/response_returned_from_function", port)));
EXPECT_EQ("", response.body);
EXPECT_EQ(204, static_cast(response.code));
EXPECT_TRUE(response.headers.Has("X-Meh"));
@@ -702,14 +640,12 @@ TEST(HTTPAPI, FourOhFiveMethodNotAllowed) {
auto& http_server = HTTP(std::move(reserved_port));
EXPECT_EQ("METHOD NOT ALLOWED
\n", DefaultMethodNotAllowedMessage());
- const auto scope = http_server
- .Register("/method_not_allowed",
- [](Request r) {
- r(DefaultMethodNotAllowedMessage(),
- HTTPResponseCode.MethodNotAllowed,
- current::net::http::Headers(),
- current::net::constants::kDefaultHTMLContentType);
- });
+ const auto scope = http_server.Register("/method_not_allowed", [](Request r) {
+ r(DefaultMethodNotAllowedMessage(),
+ HTTPResponseCode.MethodNotAllowed,
+ current::net::http::Headers(),
+ current::net::constants::kDefaultHTMLContentType);
+ });
const string url = Printf("http://localhost:%d/method_not_allowed", port);
const auto response = HTTP(GET(url));
EXPECT_EQ(405, static_cast(response.code));
@@ -742,12 +678,10 @@ TEST(HTTPAPI, DefaultInternalServerErrorCausedByExceptionInHandler) {
auto& http_server = HTTP(std::move(reserved_port));
EXPECT_EQ("INTERNAL SERVER ERROR
\n", DefaultInternalServerErrorMessage());
- const auto scope = http_server
- .Register("/oh_snap",
- [](Request) {
- // Only `current::Exception` is caught and handled.
- CURRENT_THROW(current::Exception());
- });
+ const auto scope = http_server.Register("/oh_snap", [](Request) {
+ // Only `current::Exception` is caught and handled.
+ CURRENT_THROW(current::Exception());
+ });
const string url = Printf("http://localhost:%d/oh_snap", port);
const auto response = HTTP(GET(url));
EXPECT_EQ(500, static_cast(response.code));
@@ -771,8 +705,7 @@ TEST(HTTPAPI, HandlerIsCapturedByReference) {
Helper copy(helper);
EXPECT_EQ(0u, helper.counter);
EXPECT_EQ(0u, copy.counter);
- const auto scope = http_server.Register("/incr", helper) +
- http_server.Register("/incr_same", helper) +
+ const auto scope = http_server.Register("/incr", helper) + http_server.Register("/incr_same", helper) +
http_server.Register("/incr_copy", copy);
EXPECT_EQ("Incremented two.", HTTP(GET(Printf("http://localhost:%d/incr", port))).body);
EXPECT_EQ(1u, helper.counter);
@@ -795,8 +728,7 @@ TEST(HTTPAPI, HandlerSupportsStaticMethods) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server.Register("/foo", Static::Foo) +
- http_server.Register("/bar", Static::Bar);
+ const auto scope = http_server.Register("/foo", Static::Foo) + http_server.Register("/bar", Static::Bar);
EXPECT_EQ("foo", HTTP(GET(Printf("http://localhost:%d/foo", port))).body);
EXPECT_EQ("bar", HTTP(GET(Printf("http://localhost:%d/bar", port))).body);
}
@@ -813,33 +745,31 @@ TEST(HTTPAPI, GetToFile) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/stars",
- [](Request r) {
- const size_t n = atoi(r.url.query["n"].c_str());
- auto response = r.connection.SendChunkedHTTPResponse();
- const auto sleep = []() {
- const uint64_t delay_between_chunks = []() {
- bool& reduce = Singleton().yes;
- if (!reduce) {
- reduce = true;
- return 10;
- } else {
- return 1;
- }
- }();
- std::this_thread::sleep_for(std::chrono::milliseconds(delay_between_chunks));
- };
- sleep();
- for (size_t i = 0; i < n; ++i) {
- response.Send("*");
- sleep();
- response.Send(std::vector({'a', 'b'}));
- sleep();
- response.Send(std::vector({0x31, 0x32}));
- sleep();
- }
- });
+ const auto scope = http_server.Register("/stars", [](Request r) {
+ const size_t n = atoi(r.url.query["n"].c_str());
+ auto response = r.connection.SendChunkedHTTPResponse();
+ const auto sleep = []() {
+ const uint64_t delay_between_chunks = []() {
+ bool& reduce = Singleton().yes;
+ if (!reduce) {
+ reduce = true;
+ return 10;
+ } else {
+ return 1;
+ }
+ }();
+ std::this_thread::sleep_for(std::chrono::milliseconds(delay_between_chunks));
+ };
+ sleep();
+ for (size_t i = 0; i < n; ++i) {
+ response.Send("*");
+ sleep();
+ response.Send(std::vector({'a', 'b'}));
+ sleep();
+ response.Send(std::vector({0x31, 0x32}));
+ sleep();
+ }
+ });
current::FileSystem::MkDir(FLAGS_net_api_test_tmpdir, FileSystem::MkDirParameters::Silent);
const string file_name = FLAGS_net_api_test_tmpdir + "/some_test_file_for_http_get";
const auto test_file_scope = FileSystem::ScopedRmFile(file_name);
@@ -856,16 +786,14 @@ TEST(HTTPAPI, ChunkedResponseWithHeaders) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/chunked_with_header",
- [](Request r) {
- EXPECT_EQ("GET", r.method);
- auto response = r.connection.SendChunkedHTTPResponse(
- HTTPResponseCode.OK, Headers({{"header", "yeah"}}), "text/plain");
- response.Send("A");
- response.Send("B");
- response.Send("C");
- });
+ const auto scope = http_server.Register("/chunked_with_header", [](Request r) {
+ EXPECT_EQ("GET", r.method);
+ auto response =
+ r.connection.SendChunkedHTTPResponse(HTTPResponseCode.OK, Headers({{"header", "yeah"}}), "text/plain");
+ response.Send("A");
+ response.Send("B");
+ response.Send("C");
+ });
const auto response = HTTP(GET(Printf("http://localhost:%d/chunked_with_header", port)));
EXPECT_EQ(200, static_cast(response.code));
EXPECT_EQ("ABC", response.body);
@@ -881,15 +809,13 @@ TEST(HTTPAPI, GetByChunksPrototype) {
auto& http_server = HTTP(std::move(reserved_port));
// Handler returning the result chunk by chunk.
- const auto scope = http_server
- .Register("/chunks",
- [](Request r) {
- auto response = r.connection.SendChunkedHTTPResponse(
- HTTPResponseCode.OK, Headers({{"header", "oh-well"}}), "text/plain");
- response.Send("1\n");
- response.Send("23\n");
- response.Send("456\n");
- });
+ const auto scope = http_server.Register("/chunks", [](Request r) {
+ auto response =
+ r.connection.SendChunkedHTTPResponse(HTTPResponseCode.OK, Headers({{"header", "oh-well"}}), "text/plain");
+ response.Send("1\n");
+ response.Send("23\n");
+ response.Send("456\n");
+ });
const string url = Printf("http://localhost:%d/chunks", port);
{
// A conventional GET, ignoring chunk boundaries and concatenating all the data together.
@@ -951,10 +877,12 @@ TEST(HTTPAPI, GetByChunksPrototype) {
std::vector headers;
std::vector chunk_by_chunk_response;
- const auto header_callback =
- [&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); };
- const auto chunk_callback =
- [&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); };
+ const auto header_callback = [&headers](const std::string& k, const std::string& v) {
+ headers.push_back(k + '=' + v);
+ };
+ const auto chunk_callback = [&chunk_by_chunk_response](const std::string& s) {
+ chunk_by_chunk_response.push_back(s);
+ };
const auto done_callback = [&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); };
current::http::GenericHTTPClientPOSIX client(
@@ -972,11 +900,11 @@ TEST(HTTPAPI, GetByChunksPrototype) {
std::vector headers;
std::vector chunk_by_chunk_response;
- const auto response =
- HTTP(ChunkedGET(url,
- [&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); },
- [&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); },
- [&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); }));
+ const auto response = HTTP(ChunkedGET(
+ url,
+ [&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); },
+ [&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); },
+ [&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); }));
EXPECT_EQ(200, static_cast(response));
EXPECT_EQ("1\n|23\n|456\n|DONE", current::strings::Join(chunk_by_chunk_response, '|'));
EXPECT_EQ(4u, headers.size());
@@ -1039,72 +967,74 @@ TEST(HTTPAPI, ChunkedBodySemantics) {
std::vector headers;
std::vector chunk_by_chunk_response;
- const auto response =
- HTTP(ChunkedGET(url,
- [&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); },
- [&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); },
- [&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); }));
+ const auto response = HTTP(ChunkedGET(
+ url,
+ [&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); },
+ [&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); },
+ [&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); }));
EXPECT_EQ(200, static_cast(response));
- EXPECT_EQ(
- "{\"s\":|\"foo\"|}\n{\"s\":\"bar\"}\n|{\"s\":\"baz\"}|DONE",
- current::strings::Join(chunk_by_chunk_response, '|'));
+ EXPECT_EQ("{\"s\":|\"foo\"|}\n{\"s\":\"bar\"}\n|{\"s\":\"baz\"}|DONE",
+ current::strings::Join(chunk_by_chunk_response, '|'));
EXPECT_EQ(4u, headers.size());
- EXPECT_EQ("Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive"
- "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked",
- current::strings::Join(headers, '|'));
+ EXPECT_EQ(
+ "Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive"
+ "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked",
+ current::strings::Join(headers, '|'));
}
{
std::vector headers;
std::vector chunk_by_chunk_response;
- const auto response = HTTP(ChunkedGET(url)
- .OnHeader([&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); })
- .OnChunk([&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); })
- .OnDone([&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); }));
+ const auto response =
+ HTTP(ChunkedGET(url)
+ .OnHeader([&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); })
+ .OnChunk([&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); })
+ .OnDone([&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); }));
EXPECT_EQ(200, static_cast(response));
- EXPECT_EQ(
- "{\"s\":|\"foo\"|}\n{\"s\":\"bar\"}\n|{\"s\":\"baz\"}|DONE",
- current::strings::Join(chunk_by_chunk_response, '|'));
+ EXPECT_EQ("{\"s\":|\"foo\"|}\n{\"s\":\"bar\"}\n|{\"s\":\"baz\"}|DONE",
+ current::strings::Join(chunk_by_chunk_response, '|'));
EXPECT_EQ(4u, headers.size());
- EXPECT_EQ("Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive"
- "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked",
- current::strings::Join(headers, '|'));
+ EXPECT_EQ(
+ "Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive"
+ "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked",
+ current::strings::Join(headers, '|'));
}
{
std::vector headers;
std::vector chunk_by_chunk_response;
- const auto response = HTTP(ChunkedPOST(url, "test")
- .OnHeader([&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); })
- .OnChunk([&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); })
- .OnDone([&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); }));
+ const auto response =
+ HTTP(ChunkedPOST(url, "test")
+ .OnHeader([&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); })
+ .OnChunk([&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); })
+ .OnDone([&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); }));
EXPECT_EQ(200, static_cast(response));
- EXPECT_EQ(
- "{\"s\":|\"foo\"|}\n{\"s\":\"test\"}\n|{\"s\":\"baz\"}|DONE",
- current::strings::Join(chunk_by_chunk_response, '|'));
+ EXPECT_EQ("{\"s\":|\"foo\"|}\n{\"s\":\"test\"}\n|{\"s\":\"baz\"}|DONE",
+ current::strings::Join(chunk_by_chunk_response, '|'));
EXPECT_EQ(4u, headers.size());
- EXPECT_EQ("Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive"
- "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked",
- current::strings::Join(headers, '|'));
+ EXPECT_EQ(
+ "Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive"
+ "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked",
+ current::strings::Join(headers, '|'));
}
{
std::vector headers;
std::vector line_by_line_response;
- const auto response = HTTP(ChunkedPOST(url, "passed")
- .OnHeader([&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); })
- .OnLine([&line_by_line_response](const std::string& s) { line_by_line_response.push_back(s); }));
+ const auto response =
+ HTTP(ChunkedPOST(url, "passed")
+ .OnHeader([&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); })
+ .OnLine([&line_by_line_response](const std::string& s) { line_by_line_response.push_back(s); }));
EXPECT_EQ(200, static_cast(response));
- EXPECT_EQ(
- "{\"s\":\"foo\"}|{\"s\":\"passed\"}|{\"s\":\"baz\"}",
- current::strings::Join(line_by_line_response, '|'));
+ EXPECT_EQ("{\"s\":\"foo\"}|{\"s\":\"passed\"}|{\"s\":\"baz\"}", current::strings::Join(line_by_line_response, '|'));
EXPECT_EQ(4u, headers.size());
- EXPECT_EQ("Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive"
- "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked",
- current::strings::Join(headers, '|'));
+ EXPECT_EQ(
+ "Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive"
+ "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked",
+ current::strings::Join(headers, '|'));
}
{
@@ -1125,14 +1055,11 @@ TEST(HTTPAPI, PostFromBufferToBuffer) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/post",
- [](Request r) {
- ASSERT_FALSE(r.body.empty());
- r("Data: " + r.body);
- });
- const auto response =
- HTTP(POST(Printf("http://localhost:%d/post", port), "No shit!", "application/octet-stream"));
+ const auto scope = http_server.Register("/post", [](Request r) {
+ ASSERT_FALSE(r.body.empty());
+ r("Data: " + r.body);
+ });
+ const auto response = HTTP(POST(Printf("http://localhost:%d/post", port), "No shit!", "application/octet-stream"));
EXPECT_EQ("Data: No shit!", response.body);
}
@@ -1141,17 +1068,13 @@ TEST(HTTPAPI, PostAStringAsString) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/post_string",
- [](Request r) {
- ASSERT_FALSE(r.body.empty());
- EXPECT_EQ("POST", r.method);
- r(r.body);
- });
+ const auto scope = http_server.Register("/post_string", [](Request r) {
+ ASSERT_FALSE(r.body.empty());
+ EXPECT_EQ("POST", r.method);
+ r(r.body);
+ });
EXPECT_EQ("std::string",
- HTTP(POST(Printf("http://localhost:%d/post_string", port),
- std::string("std::string"),
- "text/plain")).body);
+ HTTP(POST(Printf("http://localhost:%d/post_string", port), std::string("std::string"), "text/plain")).body);
}
TEST(HTTPAPI, PostAStringAsConstCharPtr) {
@@ -1159,17 +1082,16 @@ TEST(HTTPAPI, PostAStringAsConstCharPtr) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/post_const_char_ptr",
- [](Request r) {
- ASSERT_FALSE(r.body.empty());
- EXPECT_EQ("POST", r.method);
- r(r.body);
- });
+ const auto scope = http_server.Register("/post_const_char_ptr", [](Request r) {
+ ASSERT_FALSE(r.body.empty());
+ EXPECT_EQ("POST", r.method);
+ r(r.body);
+ });
EXPECT_EQ("const char*",
HTTP(POST(Printf("http://localhost:%d/post_const_char_ptr", port),
static_cast("const char*"),
- "text/plain")).body);
+ "text/plain"))
+ .body);
}
TEST(HTTPAPI, PostWithEmptyBodyMustSetZeroContentLength) {
@@ -1177,12 +1099,10 @@ TEST(HTTPAPI, PostWithEmptyBodyMustSetZeroContentLength) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/post",
- [](Request r) {
- ASSERT_TRUE(r.body.empty());
- r("Yo!\n");
- });
+ const auto scope = http_server.Register("/post", [](Request r) {
+ ASSERT_TRUE(r.body.empty());
+ r("Yo!\n");
+ });
const auto response = HTTP(POST(Printf("http://localhost:%d/post", port), ""));
EXPECT_EQ("Yo!\n", response.body);
}
@@ -1192,15 +1112,12 @@ TEST(HTTPAPI, RespondWithStringAsString) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/respond_with_std_string",
- [](Request r) {
- EXPECT_EQ("POST", r.method);
- EXPECT_EQ("", r.body);
- r.connection.SendHTTPResponse(std::string("std::string"), HTTPResponseCode.OK);
- });
- EXPECT_EQ("std::string",
- HTTP(POST(Printf("http://localhost:%d/respond_with_std_string", port), "")).body);
+ const auto scope = http_server.Register("/respond_with_std_string", [](Request r) {
+ EXPECT_EQ("POST", r.method);
+ EXPECT_EQ("", r.body);
+ r.connection.SendHTTPResponse(std::string("std::string"), HTTPResponseCode.OK);
+ });
+ EXPECT_EQ("std::string", HTTP(POST(Printf("http://localhost:%d/respond_with_std_string", port), "")).body);
}
TEST(HTTPAPI, RespondWithStringAsConstCharPtr) {
@@ -1208,15 +1125,11 @@ TEST(HTTPAPI, RespondWithStringAsConstCharPtr) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope =
- http_server
- .Register("/respond_with_const_char_ptr",
- [](Request r) {
- EXPECT_EQ("", r.body);
- r.connection.SendHTTPResponse(static_cast("const char*"), HTTPResponseCode.OK);
- });
- EXPECT_EQ("const char*",
- HTTP(POST(Printf("http://localhost:%d/respond_with_const_char_ptr", port), "")).body);
+ const auto scope = http_server.Register("/respond_with_const_char_ptr", [](Request r) {
+ EXPECT_EQ("", r.body);
+ r.connection.SendHTTPResponse(static_cast("const char*"), HTTPResponseCode.OK);
+ });
+ EXPECT_EQ("const char*", HTTP(POST(Printf("http://localhost:%d/respond_with_const_char_ptr", port), "")).body);
}
TEST(HTTPAPI, RespondWithStringAsStringViaRequestDirectly) {
@@ -1224,16 +1137,12 @@ TEST(HTTPAPI, RespondWithStringAsStringViaRequestDirectly) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/respond_with_std_string_via_request_directly",
- [](Request r) {
- EXPECT_EQ("", r.body);
- r(std::string("std::string"), HTTPResponseCode.OK);
- });
- EXPECT_EQ(
- "std::string",
- HTTP(POST(Printf("http://localhost:%d/respond_with_std_string_via_request_directly", port),
- "")).body);
+ const auto scope = http_server.Register("/respond_with_std_string_via_request_directly", [](Request r) {
+ EXPECT_EQ("", r.body);
+ r(std::string("std::string"), HTTPResponseCode.OK);
+ });
+ EXPECT_EQ("std::string",
+ HTTP(POST(Printf("http://localhost:%d/respond_with_std_string_via_request_directly", port), "")).body);
}
TEST(HTTPAPI, RespondWithStringAsConstCharPtrViaRequestDirectly) {
@@ -1241,16 +1150,12 @@ TEST(HTTPAPI, RespondWithStringAsConstCharPtrViaRequestDirectly) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/respond_with_const_char_ptr_via_request_directly",
- [](Request r) {
- EXPECT_EQ("", r.body);
- r(static_cast("const char*"), HTTPResponseCode.OK);
- });
- EXPECT_EQ(
- "const char*",
- HTTP(POST(Printf("http://localhost:%d/respond_with_const_char_ptr_via_request_directly", port),
- "")).body);
+ const auto scope = http_server.Register("/respond_with_const_char_ptr_via_request_directly", [](Request r) {
+ EXPECT_EQ("", r.body);
+ r(static_cast("const char*"), HTTPResponseCode.OK);
+ });
+ EXPECT_EQ("const char*",
+ HTTP(POST(Printf("http://localhost:%d/respond_with_const_char_ptr_via_request_directly", port), "")).body);
}
CURRENT_STRUCT(SerializableObject) {
@@ -1259,9 +1164,7 @@ CURRENT_STRUCT(SerializableObject) {
std::string AsString() const { return Printf("%d:%s", static_cast(x), s.c_str()); }
};
-CURRENT_STRUCT(AnotherSerializableObject) {
- CURRENT_FIELD(z, uint32_t, 42u);
-};
+CURRENT_STRUCT(AnotherSerializableObject) { CURRENT_FIELD(z, uint32_t, 42u); };
CURRENT_VARIANT(SerializableVariant, SerializableObject, AnotherSerializableObject);
@@ -1278,8 +1181,7 @@ TEST(HTTPAPI, PostFromInvalidFile) {
return port;
}();
- ASSERT_THROW(HTTP(POSTFromFile(
- Printf("http://localhost:%d/foo", port), non_existent_file_name, "text/plain")),
+ ASSERT_THROW(HTTP(POSTFromFile(Printf("http://localhost:%d/foo", port), non_existent_file_name, "text/plain")),
FileException);
}
#endif
@@ -1289,12 +1191,10 @@ TEST(HTTPAPI, PostFromFileToBuffer) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/post",
- [](Request r) {
- ASSERT_FALSE(r.body.empty());
- r("Voila: " + r.body);
- });
+ const auto scope = http_server.Register("/post", [](Request r) {
+ ASSERT_FALSE(r.body.empty());
+ r("Voila: " + r.body);
+ });
current::FileSystem::MkDir(FLAGS_net_api_test_tmpdir, FileSystem::MkDirParameters::Silent);
const string file_name = FLAGS_net_api_test_tmpdir + "/some_input_test_file_for_http_post";
const auto test_file_scope = FileSystem::ScopedRmFile(file_name);
@@ -1312,12 +1212,10 @@ TEST(HTTPAPI, PostFromBufferToFile) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/post",
- [](Request r) {
- ASSERT_FALSE(r.body.empty());
- r("Meh: " + r.body);
- });
+ const auto scope = http_server.Register("/post", [](Request r) {
+ ASSERT_FALSE(r.body.empty());
+ r("Meh: " + r.body);
+ });
current::FileSystem::MkDir(FLAGS_net_api_test_tmpdir, FileSystem::MkDirParameters::Silent);
const string file_name = FLAGS_net_api_test_tmpdir + "/some_output_test_file_for_http_post";
const auto test_file_scope = FileSystem::ScopedRmFile(file_name);
@@ -1334,12 +1232,10 @@ TEST(HTTPAPI, PostFromFileToFile) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/post",
- [](Request r) {
- ASSERT_FALSE(r.body.empty());
- r("Phew: " + r.body);
- });
+ const auto scope = http_server.Register("/post", [](Request r) {
+ ASSERT_FALSE(r.body.empty());
+ r("Phew: " + r.body);
+ });
current::FileSystem::MkDir(FLAGS_net_api_test_tmpdir, FileSystem::MkDirParameters::Silent);
const string request_file_name = FLAGS_net_api_test_tmpdir + "/some_complex_request_test_file_for_http_post";
const string response_file_name = FLAGS_net_api_test_tmpdir + "/some_complex_response_test_file_for_http_post";
@@ -1360,13 +1256,11 @@ TEST(HTTPAPI, HeadRequest) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/head",
- [](Request r) {
- EXPECT_EQ("HEAD", r.method);
- ASSERT_TRUE(r.body.empty());
- r("", HTTPResponseCode.OK, Headers({{"foo", "bar"}}), "text/html");
- });
+ const auto scope = http_server.Register("/head", [](Request r) {
+ EXPECT_EQ("HEAD", r.method);
+ ASSERT_TRUE(r.body.empty());
+ r("", HTTPResponseCode.OK, Headers({{"foo", "bar"}}), "text/html");
+ });
const auto response = HTTP(HEAD(Printf("http://localhost:%d/head", port)));
EXPECT_EQ(200, static_cast(response.code));
EXPECT_TRUE(response.body.empty());
@@ -1379,14 +1273,12 @@ TEST(HTTPAPI, DeleteRequest) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/delete",
- [](Request r) {
- EXPECT_EQ("DELETE", r.method);
- ASSERT_TRUE(r.body.empty());
- SerializableObject object;
- r(object);
- });
+ const auto scope = http_server.Register("/delete", [](Request r) {
+ EXPECT_EQ("DELETE", r.method);
+ ASSERT_TRUE(r.body.empty());
+ SerializableObject object;
+ r(object);
+ });
const auto response = HTTP(DELETE(Printf("http://localhost:%d/delete", port)));
EXPECT_EQ("42:foo", ParseJSON(response.body).AsString());
EXPECT_EQ(200, static_cast(response.code));
@@ -1397,13 +1289,11 @@ TEST(HTTPAPI, PatchRequest) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/patch",
- [](Request r) {
- EXPECT_EQ("PATCH", r.method);
- EXPECT_EQ("test", r.body);
- r("Patch OK.");
- });
+ const auto scope = http_server.Register("/patch", [](Request r) {
+ EXPECT_EQ("PATCH", r.method);
+ EXPECT_EQ("test", r.body);
+ r("Patch OK.");
+ });
const auto response = HTTP(PATCH(Printf("http://localhost:%d/patch", port), "test"));
EXPECT_EQ("Patch OK.", response.body);
EXPECT_EQ(200, static_cast(response.code));
@@ -1414,8 +1304,8 @@ TEST(HTTPAPI, UserAgent) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/ua", [](Request r) { r("TODO(dkorolev): Actually get passed in user agent."); });
+ const auto scope =
+ http_server.Register("/ua", [](Request r) { r("TODO(dkorolev): Actually get passed in user agent."); });
const string url = Printf("http://localhost:%d/ua", port);
const auto response = HTTP(GET(url).UserAgent("Blah"));
EXPECT_EQ(url, response.url);
@@ -1513,98 +1403,68 @@ TEST(HTTPAPI, ServeStaticFilesFrom) {
// Redirect from directory without trailing slash to directory with trailing slash.
{
- ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/sub_dir", port))),
- HTTPRedirectNotAllowedException);
- const auto sub_dir_response =
- HTTP(GET(Printf("http://localhost:%d/sub_dir", port)).AllowRedirects());
+ ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/sub_dir", port))), HTTPRedirectNotAllowedException);
+ const auto sub_dir_response = HTTP(GET(Printf("http://localhost:%d/sub_dir", port)).AllowRedirects());
EXPECT_EQ(200, static_cast(sub_dir_response.code));
- EXPECT_EQ((
- port == 80
- ? "http://localhost/sub_dir/"
- : Printf("http://localhost:%d/sub_dir/", port)
- ), sub_dir_response.url);
+ EXPECT_EQ((port == 80 ? "http://localhost/sub_dir/" : Printf("http://localhost:%d/sub_dir/", port)),
+ sub_dir_response.url);
ASSERT_TRUE(sub_dir_response.headers.Has("Content-Type"));
EXPECT_EQ("text/html", sub_dir_response.headers.Get("Content-Type"));
EXPECT_EQ("HTML sub_dir index
", sub_dir_response.body);
}
{
- ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/sub_dir/sub_sub_dir", port))),
- HTTPRedirectNotAllowedException);
+ ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/sub_dir/sub_sub_dir", port))), HTTPRedirectNotAllowedException);
const auto sub_sub_dir_response =
HTTP(GET(Printf("http://localhost:%d/sub_dir/sub_sub_dir", port)).AllowRedirects());
EXPECT_EQ(200, static_cast(sub_sub_dir_response.code));
- EXPECT_EQ((
- port == 80
- ? "http://localhost/sub_dir/sub_sub_dir/"
- : Printf("http://localhost:%d/sub_dir/sub_sub_dir/", port)
- ), sub_sub_dir_response.url);
+ EXPECT_EQ((port == 80 ? "http://localhost/sub_dir/sub_sub_dir/"
+ : Printf("http://localhost:%d/sub_dir/sub_sub_dir/", port)),
+ sub_sub_dir_response.url);
ASSERT_TRUE(sub_sub_dir_response.headers.Has("Content-Type"));
EXPECT_EQ("text/html", sub_sub_dir_response.headers.Get("Content-Type"));
EXPECT_EQ("HTML sub_sub_dir index
", sub_sub_dir_response.body);
}
// Subdirectory index file.
- EXPECT_EQ("HTML sub_dir index
",
- HTTP(GET(Printf("http://localhost:%d/sub_dir/", port))).body);
- EXPECT_EQ("HTML sub_dir index
",
- HTTP(GET(Printf("http://localhost:%d/sub_dir/index.htm", port))).body);
+ EXPECT_EQ("HTML sub_dir index
", HTTP(GET(Printf("http://localhost:%d/sub_dir/", port))).body);
+ EXPECT_EQ("HTML sub_dir index
", HTTP(GET(Printf("http://localhost:%d/sub_dir/index.htm", port))).body);
// File in subdirectory.
- EXPECT_EQ("alert('JavaScript')",
- HTTP(GET(Printf("http://localhost:%d/sub_dir/file_in_sub_dir.js", port))).body);
+ EXPECT_EQ("alert('JavaScript')", HTTP(GET(Printf("http://localhost:%d/sub_dir/file_in_sub_dir.js", port))).body);
// Trailing slash for files should result in HTTP 404.
- EXPECT_EQ(DefaultNotFoundMessage(),
- HTTP(GET(Printf("http://localhost:%d/index.html/", port))).body);
- EXPECT_EQ(DefaultNotFoundMessage(),
- HTTP(GET(Printf("http://localhost:%d/sub_dir/index.htm/", port))).body);
+ EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/index.html/", port))).body);
+ EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/sub_dir/index.htm/", port))).body);
// Hidden files should result in HTTP 404.
EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/.DS_Store", port))).body);
- EXPECT_EQ(DefaultNotFoundMessage(),
- HTTP(GET(Printf("http://localhost:%d/sub_dir/.file_hidden", port))).body);
+ EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/sub_dir/.file_hidden", port))).body);
// Missing index file should result in HTTP 404.
- EXPECT_EQ(DefaultNotFoundMessage(),
- HTTP(GET(Printf("http://localhost:%d/sub_dir_no_index", port))).body);
- EXPECT_EQ(DefaultNotFoundMessage(),
- HTTP(GET(Printf("http://localhost:%d/sub_dir_no_index/", port))).body);
+ EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/sub_dir_no_index", port))).body);
+ EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/sub_dir_no_index/", port))).body);
// Hidden directory should result in HTTP 404.
- EXPECT_EQ(DefaultNotFoundMessage(),
- HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden", port))).body);
- EXPECT_EQ(DefaultNotFoundMessage(),
- HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden/", port))).body);
- EXPECT_EQ(DefaultNotFoundMessage(),
- HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden/index.html", port))).body);
- EXPECT_EQ(404,
- static_cast(HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden", port))).code));
- EXPECT_EQ(
- 404,
- static_cast(
- HTTP(POST(Printf("http://localhost:%d/.sub_dir_hidden/index.html", port), "")).code));
+ EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden", port))).body);
+ EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden/", port))).body);
+ EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden/index.html", port))).body);
+ EXPECT_EQ(404, static_cast(HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden", port))).code));
+ EXPECT_EQ(404, static_cast(HTTP(POST(Printf("http://localhost:%d/.sub_dir_hidden/index.html", port), "")).code));
// POST to file URL.
- EXPECT_EQ(DefaultMethodNotAllowedMessage(),
- HTTP(POST(Printf("http://localhost:%d/file.html", port), "")).body);
- EXPECT_EQ(405,
- static_cast(HTTP(POST(Printf("http://localhost:%d/file.html", port), "")).code));
+ EXPECT_EQ(DefaultMethodNotAllowedMessage(), HTTP(POST(Printf("http://localhost:%d/file.html", port), "")).body);
+ EXPECT_EQ(405, static_cast(HTTP(POST(Printf("http://localhost:%d/file.html", port), "")).code));
// PUT to file URL.
- EXPECT_EQ(DefaultMethodNotAllowedMessage(),
- HTTP(PUT(Printf("http://localhost:%d/file.html", port), "")).body);
- EXPECT_EQ(405,
- static_cast(HTTP(PUT(Printf("http://localhost:%d/file.html", port), "")).code));
+ EXPECT_EQ(DefaultMethodNotAllowedMessage(), HTTP(PUT(Printf("http://localhost:%d/file.html", port), "")).body);
+ EXPECT_EQ(405, static_cast(HTTP(PUT(Printf("http://localhost:%d/file.html", port), "")).code));
// PATCH to file URL.
- EXPECT_EQ(DefaultMethodNotAllowedMessage(),
- HTTP(PATCH(Printf("http://localhost:%d/file.html", port), "")).body);
- EXPECT_EQ(405,
- static_cast(HTTP(PATCH(Printf("http://localhost:%d/file.html", port), "")).code));
+ EXPECT_EQ(DefaultMethodNotAllowedMessage(), HTTP(PATCH(Printf("http://localhost:%d/file.html", port), "")).body);
+ EXPECT_EQ(405, static_cast(HTTP(PATCH(Printf("http://localhost:%d/file.html", port), "")).code));
// DELETE to file URL.
- EXPECT_EQ(DefaultMethodNotAllowedMessage(),
- HTTP(DELETE(Printf("http://localhost:%d/file.html", port))).body);
+ EXPECT_EQ(DefaultMethodNotAllowedMessage(), HTTP(DELETE(Printf("http://localhost:%d/file.html", port))).body);
EXPECT_EQ(405, static_cast(HTTP(DELETE(Printf("http://localhost:%d/file.html", port))).code));
}
@@ -1628,25 +1488,19 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefix) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope =
- http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/static/something"});
+ const auto scope = http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/static/something"});
// Root index file.
- EXPECT_EQ("HTML index
",
- HTTP(GET(Printf("http://localhost:%d/static/something/", port))).body);
+ EXPECT_EQ("HTML index
", HTTP(GET(Printf("http://localhost:%d/static/something/", port))).body);
// Redirect from directory without trailing slash to directory with trailing slash.
{
- ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something", port))),
- HTTPRedirectNotAllowedException);
- const auto dir_response =
- HTTP(GET(Printf("http://localhost:%d/static/something", port)).AllowRedirects());
+ ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something", port))), HTTPRedirectNotAllowedException);
+ const auto dir_response = HTTP(GET(Printf("http://localhost:%d/static/something", port)).AllowRedirects());
EXPECT_EQ(200, static_cast(dir_response.code));
- EXPECT_EQ((
- port == 80
- ? "http://localhost/static/something/"
- : Printf("http://localhost:%d/static/something/", port)
- ), dir_response.url);
+ EXPECT_EQ(
+ (port == 80 ? "http://localhost/static/something/" : Printf("http://localhost:%d/static/something/", port)),
+ dir_response.url);
EXPECT_EQ("HTML index
", dir_response.body);
}
@@ -1661,31 +1515,26 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefix) {
const auto sub_dir_response =
HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir", port)).AllowRedirects());
EXPECT_EQ(200, static_cast(sub_dir_response.code));
- EXPECT_EQ((
- port == 80
- ? "http://localhost/static/something/sub_dir/"
- : Printf("http://localhost:%d/static/something/sub_dir/", port)
- ), sub_dir_response.url);
+ EXPECT_EQ((port == 80 ? "http://localhost/static/something/sub_dir/"
+ : Printf("http://localhost:%d/static/something/sub_dir/", port)),
+ sub_dir_response.url);
EXPECT_EQ("HTML sub_dir index
", sub_dir_response.body);
}
// Subsubdirectory index file.
- EXPECT_EQ(
- "HTML sub_sub_dir index
",
- HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port))).body);
+ EXPECT_EQ("HTML sub_sub_dir index
",
+ HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port))).body);
// Redirect from subsubdirectory without trailing slash to subsubdirectory with trailing slash.
{
ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", port))),
HTTPRedirectNotAllowedException);
- const auto sub_sub_dir_response = HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir",
- port)).AllowRedirects());
+ const auto sub_sub_dir_response =
+ HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", port)).AllowRedirects());
EXPECT_EQ(200, static_cast(sub_sub_dir_response.code));
- EXPECT_EQ((
- port == 80
- ? "http://localhost/static/something/sub_dir/sub_sub_dir/"
- : Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port)
- ), sub_sub_dir_response.url);
+ EXPECT_EQ((port == 80 ? "http://localhost/static/something/sub_dir/sub_sub_dir/"
+ : Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port)),
+ sub_sub_dir_response.url);
EXPECT_EQ("HTML sub_sub_dir index
", sub_sub_dir_response.body);
}
}
@@ -1717,25 +1566,19 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefixAndPublicUrlPrefixRela
const auto scope_redirect_to =
http_server.Register("/anything", URLPathArgs::CountMask::Any, [](Request r) { r("Done."); });
- const auto scope = http_server
- .ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/static/something", "/anything"});
+ const auto scope =
+ http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/static/something", "/anything"});
// Root index file.
- EXPECT_EQ("HTML index
",
- HTTP(GET(Printf("http://localhost:%d/static/something/", port))).body);
+ EXPECT_EQ("HTML index
", HTTP(GET(Printf("http://localhost:%d/static/something/", port))).body);
// Redirect from directory without trailing slash to directory with trailing slash.
{
- ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something", port))),
- HTTPRedirectNotAllowedException);
- const auto dir_response =
- HTTP(GET(Printf("http://localhost:%d/static/something", port)).AllowRedirects());
+ ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something", port))), HTTPRedirectNotAllowedException);
+ const auto dir_response = HTTP(GET(Printf("http://localhost:%d/static/something", port)).AllowRedirects());
EXPECT_EQ(200, static_cast(dir_response.code));
- EXPECT_EQ((
- port == 80
- ? "http://localhost/anything/"
- : Printf("http://localhost:%d/anything/", port)
- ), dir_response.url);
+ EXPECT_EQ((port == 80 ? "http://localhost/anything/" : Printf("http://localhost:%d/anything/", port)),
+ dir_response.url);
EXPECT_EQ("Done.", dir_response.body);
}
@@ -1750,31 +1593,26 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefixAndPublicUrlPrefixRela
const auto sub_dir_response =
HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir", port)).AllowRedirects());
EXPECT_EQ(200, static_cast(sub_dir_response.code));
- EXPECT_EQ((
- port == 80
- ? "http://localhost/anything/sub_dir/"
- : Printf("http://localhost:%d/anything/sub_dir/", port)
- ), sub_dir_response.url);
+ EXPECT_EQ(
+ (port == 80 ? "http://localhost/anything/sub_dir/" : Printf("http://localhost:%d/anything/sub_dir/", port)),
+ sub_dir_response.url);
EXPECT_EQ("Done.", sub_dir_response.body);
}
// Subsubdirectory index file.
- EXPECT_EQ(
- "HTML sub_sub_dir index
",
- HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port))).body);
+ EXPECT_EQ("HTML sub_sub_dir index
",
+ HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port))).body);
// Redirect from subsubdirectory without trailing slash to subsubdirectory with trailing slash.
{
ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", port))),
HTTPRedirectNotAllowedException);
- const auto sub_sub_dir_response = HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir",
- port)).AllowRedirects());
+ const auto sub_sub_dir_response =
+ HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", port)).AllowRedirects());
EXPECT_EQ(200, static_cast(sub_sub_dir_response.code));
- EXPECT_EQ((
- port == 80
- ? "http://localhost/anything/sub_dir/sub_sub_dir/"
- : Printf("http://localhost:%d/anything/sub_dir/sub_sub_dir/", port)
- ), sub_sub_dir_response.url);
+ EXPECT_EQ((port == 80 ? "http://localhost/anything/sub_dir/sub_sub_dir/"
+ : Printf("http://localhost:%d/anything/sub_dir/sub_sub_dir/", port)),
+ sub_sub_dir_response.url);
EXPECT_EQ("Done.", sub_sub_dir_response.body);
}
}
@@ -1809,29 +1647,19 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefixAndPublicUrlPrefixAbso
const auto scope_redirect_to =
HTTP(std::move(second_reserved_port)).Register("/", URLPathArgs::CountMask::Any, [](Request r) { r("Done."); });
- const auto scope =
- http_server
- .ServeStaticFilesFrom(
- dir,
- ServeStaticFilesFromOptions{"/static/something",
- Printf("http://localhost:%d/anything", second_port)});
+ const auto scope = http_server.ServeStaticFilesFrom(
+ dir, ServeStaticFilesFromOptions{"/static/something", Printf("http://localhost:%d/anything", second_port)});
// Root index file.
- EXPECT_EQ("HTML index
",
- HTTP(GET(Printf("http://localhost:%d/static/something/", port))).body);
+ EXPECT_EQ("HTML index
", HTTP(GET(Printf("http://localhost:%d/static/something/", port))).body);
// Redirect from directory without trailing slash to directory with trailing slash.
{
- ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something", port))),
- HTTPRedirectNotAllowedException);
- const auto dir_response =
- HTTP(GET(Printf("http://localhost:%d/static/something", port)).AllowRedirects());
+ ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something", port))), HTTPRedirectNotAllowedException);
+ const auto dir_response = HTTP(GET(Printf("http://localhost:%d/static/something", port)).AllowRedirects());
EXPECT_EQ(200, static_cast(dir_response.code));
- EXPECT_EQ((
- second_port == 80
- ? "http://localhost/anything/"
- : Printf("http://localhost:%d/anything/", second_port)
- ), dir_response.url);
+ EXPECT_EQ((second_port == 80 ? "http://localhost/anything/" : Printf("http://localhost:%d/anything/", second_port)),
+ dir_response.url);
EXPECT_EQ("Done.", dir_response.body);
}
@@ -1846,31 +1674,26 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefixAndPublicUrlPrefixAbso
const auto sub_dir_response =
HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir", port)).AllowRedirects());
EXPECT_EQ(200, static_cast(sub_dir_response.code));
- EXPECT_EQ((
- second_port == 80
- ? "http://localhost/anything/sub_dir/"
- : Printf("http://localhost:%d/anything/sub_dir/", second_port)
- ), sub_dir_response.url);
+ EXPECT_EQ((second_port == 80 ? "http://localhost/anything/sub_dir/"
+ : Printf("http://localhost:%d/anything/sub_dir/", second_port)),
+ sub_dir_response.url);
EXPECT_EQ("Done.", sub_dir_response.body);
}
// Subsubdirectory index file.
- EXPECT_EQ(
- "HTML sub_sub_dir index
",
- HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port))).body);
+ EXPECT_EQ("HTML sub_sub_dir index
",
+ HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port))).body);
// Redirect from subsubdirectory without trailing slash to subsubdirectory with trailing slash.
{
ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", port))),
HTTPRedirectNotAllowedException);
- const auto sub_sub_dir_response = HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir",
- port)).AllowRedirects());
+ const auto sub_sub_dir_response =
+ HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", port)).AllowRedirects());
EXPECT_EQ(200, static_cast(sub_sub_dir_response.code));
- EXPECT_EQ((
- second_port == 80
- ? "http://localhost/anything/sub_dir/sub_sub_dir/"
- : Printf("http://localhost:%d/anything/sub_dir/sub_sub_dir/", second_port)
- ), sub_sub_dir_response.url);
+ EXPECT_EQ((second_port == 80 ? "http://localhost/anything/sub_dir/sub_sub_dir/"
+ : Printf("http://localhost:%d/anything/sub_dir/sub_sub_dir/", second_port)),
+ sub_sub_dir_response.url);
EXPECT_EQ("Done.", sub_sub_dir_response.body);
}
}
@@ -1882,8 +1705,7 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefixWithTrailingSlash) {
auto& http_server = HTTP(std::move(reserved_port));
const std::string dir = FileSystem::JoinPath(FLAGS_net_api_test_tmpdir, "static");
- ASSERT_THROW(http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/static/"}),
- PathEndsWithSlash);
+ ASSERT_THROW(http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/static/"}), PathEndsWithSlash);
}
TEST(HTTPAPI, ServeStaticFilesFromOptionsEmptyPublicRoutePrefix) {
@@ -1893,8 +1715,7 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsEmptyPublicRoutePrefix) {
auto& http_server = HTTP(std::move(reserved_port));
const std::string dir = FileSystem::JoinPath(FLAGS_net_api_test_tmpdir, "static");
- ASSERT_THROW(http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{""}),
- PathDoesNotStartWithSlash);
+ ASSERT_THROW(http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{""}), PathDoesNotStartWithSlash);
}
TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomIndexFiles) {
@@ -1909,8 +1730,7 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomIndexFiles) {
const auto dir_remover = current::FileSystem::ScopedRmDir(dir);
FileSystem::MkDir(dir, FileSystem::MkDirParameters::Silent);
FileSystem::WriteStringToFile("TXT index", FileSystem::JoinPath(dir, "index.txt").c_str());
- const auto scope =
- http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/", "", {"index.txt"}});
+ const auto scope = http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/", "", {"index.txt"}});
EXPECT_EQ("TXT index", HTTP(GET(Printf("http://localhost:%d/", port))).body);
EXPECT_EQ("TXT index", HTTP(GET(Printf("http://localhost:%d/index.txt", port))).body);
}
@@ -1927,8 +1747,7 @@ TEST(HTTPAPI, ServeStaticFilesFromOnlyServesOneIndexFilePerDirectory) {
FileSystem::MkDir(dir, FileSystem::MkDirParameters::Silent);
FileSystem::WriteStringToFile("HTML index 1
", FileSystem::JoinPath(dir, "index.html").c_str());
FileSystem::WriteStringToFile("HTML index 2
", FileSystem::JoinPath(dir, "index.htm").c_str());
- ASSERT_THROW(http_server.ServeStaticFilesFrom(dir),
- ServeStaticFilesFromCannotServeMoreThanOneIndexFile);
+ ASSERT_THROW(http_server.ServeStaticFilesFrom(dir), ServeStaticFilesFromCannotServeMoreThanOneIndexFile);
}
TEST(HTTPAPI, ServeStaticFilesFromOnlyServesFilesOfKnownMIMEType) {
@@ -1943,8 +1762,7 @@ TEST(HTTPAPI, ServeStaticFilesFromOnlyServesFilesOfKnownMIMEType) {
FileSystem::MkDir(dir, FileSystem::MkDirParameters::Silent);
FileSystem::WriteStringToFile("TXT is okay.", FileSystem::JoinPath(dir, "file.txt").c_str());
FileSystem::WriteStringToFile("FOO is not! ", FileSystem::JoinPath(dir, "file.foo").c_str());
- ASSERT_THROW(http_server.ServeStaticFilesFrom(dir),
- ServeStaticFilesFromCanNotServeStaticFilesOfUnknownMIMEType);
+ ASSERT_THROW(http_server.ServeStaticFilesFrom(dir), ServeStaticFilesFromCanNotServeStaticFilesOfUnknownMIMEType);
}
TEST(HTTPAPI, ResponseSmokeTest) {
@@ -1954,62 +1772,34 @@ TEST(HTTPAPI, ResponseSmokeTest) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope =
- http_server
- .Register("/response1", [send_response](Request r) { send_response(Response("foo"), std::move(r)); }) +
- http_server
- .Register(
- "/response2",
- [send_response](Request r) { send_response(Response("bar", HTTPResponseCode.Accepted), std::move(r)); }) +
- http_server
- .Register("/response3",
- [send_response](Request r) {
- send_response(Response("baz", HTTPResponseCode.NotFound, "text/blah"), std::move(r));
- }) +
- http_server
- .Register("/response4",
- [send_response](Request r) {
- send_response(Response(SerializableObject(), HTTPResponseCode.Accepted), std::move(r));
- }) +
- http_server
- .Register("/response5",
- [send_response](Request r) {
- send_response(Response(SerializableObject(), "meh").Code(HTTPResponseCode.Created), std::move(r));
- }) +
- http_server
- .Register("/response6",
- [send_response](Request r) {
- send_response(Response().Body("OK").Code(HTTPResponseCode.OK), std::move(r));
- }) +
- http_server
- .Register("/response7",
- [send_response](Request r) {
- send_response(Response().JSON(SerializableObject(), "magic").Code(HTTPResponseCode.OK),
- std::move(r));
- }) +
- http_server
- .Register("/response8",
- [send_response](Request r) { send_response(Response(HTTPResponseCode.Created), std::move(r)); }) +
- http_server
- .Register("/response9",
- [send_response](Request r) {
- send_response(Response(), std::move(r)); // Will result in a 500 "INTERNAL SERVER ERROR".
- }) +
- http_server
- .Register("/response10",
- [](Request r) {
- SerializableVariant v;
- v.template Construct();
- r(v);
- }) +
- http_server
- .Register("/response11",
- [send_response](Request r) {
- // Test both a direct response (`Request::operator()`) and a response via `Respose`.
- SerializableVariant v;
- v.template Construct();
- send_response(v, std::move(r));
- });
+ const auto scope = http_server.Register("/response1", [send_response](Request r) {
+ send_response(Response("foo"), std::move(r));
+ }) + http_server.Register("/response2", [send_response](Request r) {
+ send_response(Response("bar", HTTPResponseCode.Accepted), std::move(r));
+ }) + http_server.Register("/response3", [send_response](Request r) {
+ send_response(Response("baz", HTTPResponseCode.NotFound, "text/blah"), std::move(r));
+ }) + http_server.Register("/response4", [send_response](Request r) {
+ send_response(Response(SerializableObject(), HTTPResponseCode.Accepted), std::move(r));
+ }) + http_server.Register("/response5", [send_response](Request r) {
+ send_response(Response(SerializableObject(), "meh").Code(HTTPResponseCode.Created), std::move(r));
+ }) + http_server.Register("/response6", [send_response](Request r) {
+ send_response(Response().Body("OK").Code(HTTPResponseCode.OK), std::move(r));
+ }) + http_server.Register("/response7", [send_response](Request r) {
+ send_response(Response().JSON(SerializableObject(), "magic").Code(HTTPResponseCode.OK), std::move(r));
+ }) + http_server.Register("/response8", [send_response](Request r) {
+ send_response(Response(HTTPResponseCode.Created), std::move(r));
+ }) + http_server.Register("/response9", [send_response](Request r) {
+ send_response(Response(), std::move(r)); // Will result in a 500 "INTERNAL SERVER ERROR".
+ }) + http_server.Register("/response10", [](Request r) {
+ SerializableVariant v;
+ v.template Construct();
+ r(v);
+ }) + http_server.Register("/response11", [send_response](Request r) {
+ // Test both a direct response (`Request::operator()`) and a response via `Respose`.
+ SerializableVariant v;
+ v.template Construct();
+ send_response(v, std::move(r));
+ });
const auto response1 = HTTP(GET(Printf("http://localhost:%d/response1", port)));
EXPECT_EQ(200, static_cast(response1.code));
@@ -2068,20 +1858,17 @@ TEST(HTTPAPI, PayloadTooLarge) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope = http_server
- .Register("/enough_is_enough",
- [](Request r) {
- ASSERT_FALSE(r.body.empty());
- EXPECT_EQ("POST", r.method);
- r("Fits.\n");
- });
+ const auto scope = http_server.Register("/enough_is_enough", [](Request r) {
+ ASSERT_FALSE(r.body.empty());
+ EXPECT_EQ("POST", r.method);
+ r("Fits.\n");
+ });
{
const size_t size_ok = 16 * 1024 * 1024;
ASSERT_EQ(current::net::constants::kMaxHTTPPayloadSizeInBytes, size_ok);
- const auto response =
- HTTP(POST(Printf("http://localhost:%d/enough_is_enough", port), std::string(size_ok, '.')));
+ const auto response = HTTP(POST(Printf("http://localhost:%d/enough_is_enough", port), std::string(size_ok, '.')));
EXPECT_EQ(200, static_cast(response.code));
EXPECT_EQ("Fits.\n", response.body);
}
@@ -2089,8 +1876,8 @@ TEST(HTTPAPI, PayloadTooLarge) {
const size_t size_too_much = 16 * 1024 * 1024 + 1;
ASSERT_GT(size_too_much, current::net::constants::kMaxHTTPPayloadSizeInBytes);
- const auto response = HTTP(
- POST(Printf("http://localhost:%d/enough_is_enough", port), std::string(size_too_much, '.')));
+ const auto response =
+ HTTP(POST(Printf("http://localhost:%d/enough_is_enough", port), std::string(size_too_much, '.')));
EXPECT_EQ(413, static_cast(response.code));
EXPECT_EQ("ENTITY TOO LARGE
\n", response.body);
}
@@ -2108,23 +1895,18 @@ TEST(HTTPAPI, ResponseGeneratorForSerializableAndNonSerializableTypes) {
const int port = reserved_port;
auto& http_server = HTTP(std::move(reserved_port));
- const auto scope =
- http_server
- .Register(
- "/maybe_json",
- [](Request r) {
- if (r.url.query.has("json")) {
- static_assert(current::serialization::json::IsJSONSerializable::value, "");
- r(current::http::GenerateResponseFromMaybeSerializableObject<
- HTTPAPITemplatedTestObject>(HTTPAPITemplatedTestObject()));
- } else {
- static_assert(!current::serialization::json::IsJSONSerializable::value,
- "");
- r(current::http::GenerateResponseFromMaybeSerializableObject<
- HTTPAPITemplatedTestObject>(
- HTTPAPITemplatedTestObject()));
- }
- });
+ const auto scope = http_server.Register("/maybe_json", [](Request r) {
+ if (r.url.query.has("json")) {
+ static_assert(current::serialization::json::IsJSONSerializable::value, "");
+ r(current::http::GenerateResponseFromMaybeSerializableObject>(
+ HTTPAPITemplatedTestObject()));
+ } else {
+ static_assert(!current::serialization::json::IsJSONSerializable::value, "");
+ r(current::http::GenerateResponseFromMaybeSerializableObject<
+ HTTPAPITemplatedTestObject>(
+ HTTPAPITemplatedTestObject()));
+ }
+ });
{
const auto response = HTTP(GET(Printf("http://localhost:%d/maybe_json?json", port)));
EXPECT_EQ("{\"text\":\"OK\",\"data\":{\"number\":42,\"text\":\"text\",\"array\":[1,2,3]}}\n", response.body);
@@ -2178,8 +1960,7 @@ TEST(HTTPAPI, JSONDoesHaveCORSHeaderByDefault) {
auto& http_server = HTTP(std::move(reserved_port));
{
- const auto scope =
- http_server.Register("/json1", [](Request r) { r(Response(SerializableObject())); });
+ const auto scope = http_server.Register("/json1", [](Request r) { r(Response(SerializableObject())); });
const auto response = HTTP(GET(Printf("http://localhost:%d/json1", port)));
EXPECT_EQ(200, static_cast(response.code));
@@ -2188,9 +1969,8 @@ TEST(HTTPAPI, JSONDoesHaveCORSHeaderByDefault) {
EXPECT_EQ("*", response.headers.Get("Access-Control-Allow-Origin"));
}
{
- const auto scope = http_server.Register("/json2", [](Request r) {
- r(Response(SerializableObject()).DisableCORS());
- });
+ const auto scope =
+ http_server.Register("/json2", [](Request r) { r(Response(SerializableObject()).DisableCORS()); });
const auto response = HTTP(GET(Printf("http://localhost:%d/json2", port)));
EXPECT_EQ(200, static_cast(response.code));
@@ -2198,9 +1978,8 @@ TEST(HTTPAPI, JSONDoesHaveCORSHeaderByDefault) {
EXPECT_FALSE(response.headers.Has("Access-Control-Allow-Origin"));
}
{
- const auto scope = http_server.Register("/json3", [](Request r) {
- r(Response(SerializableObject()).DisableCORS().EnableCORS());
- });
+ const auto scope =
+ http_server.Register("/json3", [](Request r) { r(Response(SerializableObject()).DisableCORS().EnableCORS()); });
const auto response = HTTP(GET(Printf("http://localhost:%d/json3", port)));
EXPECT_EQ(200, static_cast(response.code));
diff --git a/blocks/http/types.h b/blocks/http/types.h
index f6dc9ac7f..2ea97d2c4 100644
--- a/blocks/http/types.h
+++ b/blocks/http/types.h
@@ -103,15 +103,16 @@ struct ChunkedBase {
std::function done_callback_impl;
explicit ChunkedBase(std::string url)
- : url(std::move(url)),
- header_callback([this](const std::string& k, const std::string& v) { header_callback_wrapper(k, v); }),
- chunk_callback([this](const std::string& c) { chunk_callback_wrapper(c); }),
- done_callback([this]() { done_callback_wrapper(); }) {}
-
- explicit ChunkedBase(std::string url,
- std::function header_callback,
- std::function chunk_callback,
- std::function done_callback = []() {})
+ : url(std::move(url)),
+ header_callback([this](const std::string& k, const std::string& v) { header_callback_wrapper(k, v); }),
+ chunk_callback([this](const std::string& c) { chunk_callback_wrapper(c); }),
+ done_callback([this]() { done_callback_wrapper(); }) {}
+
+ explicit ChunkedBase(
+ std::string url,
+ std::function header_callback,
+ std::function chunk_callback,
+ std::function done_callback = []() {})
: ChunkedBase(std::move(url)) {
header_callback_impl = header_callback;
chunk_callback_impl = chunk_callback;
@@ -135,7 +136,7 @@ struct ChunkedBase {
// TODO(dkorolev): Move this to `Chunk`-s if performance becomes the bottleneck.
T& OnLine(std::function line_callback) {
group_by_lines_.emplace_back(std::make_unique(
- [line_callback](const std::string& line) { line_callback(line); }));
+ [line_callback](const std::string& line) { line_callback(line); }));
return static_cast(*this);
}
@@ -168,12 +169,13 @@ struct ChunkedGET final : ChunkedBase {
struct ChunkedPOST final : ChunkedBase {
const std::string body;
const std::string content_type;
- explicit ChunkedPOST(std::string url,
- std::string body,
- std::string content_type,
- std::function header_callback,
- std::function chunk_callback,
- std::function done_callback = []() {})
+ explicit ChunkedPOST(
+ std::string url,
+ std::string body,
+ std::string content_type,
+ std::function header_callback,
+ std::function chunk_callback,
+ std::function done_callback = []() {})
: ChunkedBase(std::move(url), header_callback, chunk_callback, done_callback),
body(std::move(body)),
content_type(std::move(content_type)) {}
@@ -202,8 +204,9 @@ struct FillBody {
template
struct FillBody {
template
- static std::enable_if_t)> Fill(
- REQUEST& request, T&& object, const std::string& content_type) {
+ static std::enable_if_t)> Fill(REQUEST& request,
+ T&& object,
+ const std::string& content_type) {
request.body = JSON(std::forward(object));
request.content_type = !content_type.empty() ? content_type : net::constants::kDefaultJSONContentType;
}
@@ -214,8 +217,7 @@ struct POST : HTTPRequestBase {
std::string content_type;
template
- POST(const std::string& url, T&& body, const std::string& content_type = "")
- : HTTPRequestBase(url) {
+ POST(const std::string& url, T&& body, const std::string& content_type = "") : HTTPRequestBase(url) {
FillBody::value>::Fill(*this, std::forward(body), content_type);
}
};
@@ -233,8 +235,7 @@ struct PUT : HTTPRequestBase {
std::string content_type;
template
- PUT(const std::string& url, T&& body, const std::string& content_type = "")
- : HTTPRequestBase(url) {
+ PUT(const std::string& url, T&& body, const std::string& content_type = "") : HTTPRequestBase(url) {
FillBody::value>::Fill(*this, std::forward(body), content_type);
}
};
@@ -244,8 +245,7 @@ struct PATCH : HTTPRequestBase {
std::string content_type;
template
- PATCH(const std::string& url, T&& body, const std::string& content_type = "")
- : HTTPRequestBase(url) {
+ PATCH(const std::string& url, T&& body, const std::string& content_type = "") : HTTPRequestBase(url) {
FillBody::value>::Fill(*this, std::forward(body), content_type);
}
};
@@ -398,13 +398,13 @@ struct HTTPImpl {
} // namespace http
} // namespace current
+using current::http::DELETE;
using current::http::GET;
using current::http::HEAD;
+using current::http::PATCH;
using current::http::POST;
using current::http::POSTFromFile;
using current::http::PUT;
-using current::http::PATCH;
-using current::http::DELETE;
using current::http::ChunkedGET;
using current::http::ChunkedPOST;
diff --git a/blocks/json/json.h b/blocks/json/json.h
index c282c9aec..6ad0f55fd 100644
--- a/blocks/json/json.h
+++ b/blocks/json/json.h
@@ -75,14 +75,14 @@ CURRENT_STRUCT(JSONString) {
CURRENT_FIELD(string, std::string);
CURRENT_CONSTRUCTOR(JSONString)(std::string string = "") : string(std::move(string)) {}
operator std::string() const { return string; }
- void DoAppendToJSON(std::ostream& os) const { os << JSON(string); }
+ void DoAppendToJSON(std::ostream & os) const { os << JSON(string); }
};
CURRENT_STRUCT(JSONNumber) {
CURRENT_FIELD(number, double);
CURRENT_CONSTRUCTOR(JSONNumber)(double number = 0) : number(number) {}
operator double() const { return number; }
- void DoAppendToJSON(std::ostream& os) const {
+ void DoAppendToJSON(std::ostream & os) const {
if (number == std::floor(number)) {
if (number < 0) {
os << JSON(static_cast(number));
@@ -99,7 +99,7 @@ CURRENT_STRUCT(JSONBoolean) {
CURRENT_FIELD(boolean, bool);
CURRENT_CONSTRUCTOR(JSONBoolean)(bool boolean = false) : boolean(boolean) {}
operator bool() const { return boolean; }
- void DoAppendToJSON(std::ostream& os) const { os << JSON(boolean); }
+ void DoAppendToJSON(std::ostream & os) const { os << JSON(boolean); }
};
// clang-format off
@@ -119,7 +119,7 @@ CURRENT_STRUCT(JSONArray) {
static JSONValue null((JSONNull()));
return i < elements.size() ? elements[i] : null;
}
- void DoAppendToJSON(std::ostream& os) const {
+ void DoAppendToJSON(std::ostream & os) const {
os << '[';
bool first = true;
for (const JSONValue& element : elements) {
@@ -133,19 +133,11 @@ CURRENT_STRUCT(JSONArray) {
os << ']';
}
using iterator = typename std::vector::iterator;
- iterator begin() {
- return elements.begin();
- }
- iterator end() {
- return elements.end();
- }
+ iterator begin() { return elements.begin(); }
+ iterator end() { return elements.end(); }
using const_iterator = typename std::vector::const_iterator;
- const_iterator begin() const {
- return elements.begin();
- }
- const_iterator end() const {
- return elements.end();
- }
+ const_iterator begin() const { return elements.begin(); }
+ const_iterator end() const { return elements.end(); }
};
CURRENT_STRUCT(JSONObject) {
@@ -176,7 +168,7 @@ CURRENT_STRUCT(JSONObject) {
fields.erase(name);
return *this;
}
- void DoAppendToJSON(std::ostream& os) const {
+ void DoAppendToJSON(std::ostream & os) const {
os << '{';
bool first = true;
for (const std::string& key : keys) {
@@ -201,19 +193,11 @@ CURRENT_STRUCT(JSONObject) {
const_iterator(const JSONObject& self, std::vector::const_iterator cit) : self(self), cit(cit) {}
bool operator==(const const_iterator& rhs) const { return cit == rhs.cit; }
bool operator!=(const const_iterator& rhs) const { return cit != rhs.cit; }
- const_element operator*() const {
- return const_element(*cit, self.fields.at(*cit));
- }
- void operator++() {
- ++cit;
- }
+ const_element operator*() const { return const_element(*cit, self.fields.at(*cit)); }
+ void operator++() { ++cit; }
};
- const_iterator begin() const {
- return const_iterator(*this, keys.begin());
- }
- const_iterator end() const {
- return const_iterator(*this, keys.end());
- }
+ const_iterator begin() const { return const_iterator(*this, keys.begin()); }
+ const_iterator end() const { return const_iterator(*this, keys.end()); }
};
inline JSONValue ParseJSONUniversally(rapidjson::Value& value) {
diff --git a/blocks/json/test.cc b/blocks/json/test.cc
index b1eb76b3e..8402b8e52 100644
--- a/blocks/json/test.cc
+++ b/blocks/json/test.cc
@@ -121,9 +121,8 @@ TEST(UniversalJSON, Object) {
using JO = JSONObject;
using JN = JSONNumber;
- EXPECT_EQ(
- "{\"x\":42,\"y\":{\"a\":1,\"b\":2}}",
- AsJSON(JO().push_back("x", JN(42)).push_back("y", JO().push_back("a", JN(1)).push_back("b", JN(2)))));
+ EXPECT_EQ("{\"x\":42,\"y\":{\"a\":1,\"b\":2}}",
+ AsJSON(JO().push_back("x", JN(42)).push_back("y", JO().push_back("a", JN(1)).push_back("b", JN(2)))));
}
TEST(UniversalJSON, FloatingPoint) {
diff --git a/blocks/mmq/mmpq.h b/blocks/mmq/mmpq.h
index 395110460..879ff749f 100644
--- a/blocks/mmq/mmpq.h
+++ b/blocks/mmq/mmpq.h
@@ -108,11 +108,9 @@ class MMPQImpl {
while (true) {
std::unique_lock lock(mutex_);
- condition_variable_.wait(lock,
- [this] {
- return (!queue_.empty() && queue_.begin()->index_timestamp.us <= last_idx_ts_.us) ||
- destructing_;
- });
+ condition_variable_.wait(lock, [this] {
+ return (!queue_.empty() && queue_.begin()->index_timestamp.us <= last_idx_ts_.us) || destructing_;
+ });
if (destructing_) {
return; // LCOV_EXCL_LINE
diff --git a/blocks/mmq/test.cc b/blocks/mmq/test.cc
index 109e9129d..7d79e58c3 100644
--- a/blocks/mmq/test.cc
+++ b/blocks/mmq/test.cc
@@ -37,8 +37,8 @@ SOFTWARE.
#include "../../3rdparty/gtest/gtest-main.h"
-using current::mmq::MMQ;
using current::mmq::MMPQ;
+using current::mmq::MMQ;
using current::ss::EntryResponse;
TEST(InMemoryMQ, SmokeTest) {
diff --git a/blocks/persistence/exceptions.h b/blocks/persistence/exceptions.h
index 3cd59cc84..d27d3a563 100644
--- a/blocks/persistence/exceptions.h
+++ b/blocks/persistence/exceptions.h
@@ -70,7 +70,7 @@ struct UnsafePublishBadIndexTimestampException : PersistenceException {
"Expecting index %lld, seeing %lld.", static_cast(expected), static_cast(found))) {}
};
-} // namespace peristence
+} // namespace persistence
} // namespace current
#endif // BLOCKS_PERSISTENCE_EXCEPTIONS_H
diff --git a/blocks/persistence/file.h b/blocks/persistence/file.h
index b971a39bd..f74387d41 100644
--- a/blocks/persistence/file.h
+++ b/blocks/persistence/file.h
@@ -61,7 +61,7 @@ constexpr char kDirectiveMarker = '#';
constexpr char kSignatureDirective[] = "#signature";
constexpr char kHeadDirective[] = "#head";
constexpr char kHeadFormatString[] = "%020lld";
-} // namespace current::persistence::impl::constants
+} // namespace constants
typedef int64_t head_value_t;
@@ -460,7 +460,8 @@ class FilePersister {
// would be serialized in an unwrapped way when passed directly.
file_persister_impl_->file_appender_ << JSON(idxts) << '\t'
<< JSON(MakeSureTheRightTypeIsSerialized>::DoIt(
- std::forward(entry))) << std::endl;
+ std::forward(entry)))
+ << std::endl;
++iterator.next_index;
file_persister_impl_->head_offset_ = 0;
file_persister_impl_->end_.store(iterator);
@@ -630,7 +631,10 @@ class FilePersister {
// ">" is OK, as this call is multithreading-friendly, and more entries could have been added during this call.
CURRENT_ASSERT(file_persister_impl_->record_offset_.size() >= current_size);
- return ITERABLE(file_persister_impl_, static_cast(begin_index), static_cast(end_index), file_persister_impl_->record_offset_[static_cast(begin_index)]);
+ return ITERABLE(file_persister_impl_,
+ static_cast(begin_index),
+ static_cast(end_index),
+ file_persister_impl_->record_offset_[static_cast(begin_index)]);
}
template
@@ -651,12 +655,12 @@ class FilePersister {
Owned file_persister_impl_; // `Owned`, as iterators borrow it.
};
-} // namespace current::persistence::impl
+} // namespace impl
template
using File = ss::EntryPersister, ENTRY>;
-} // namespace current::persistence
+} // namespace persistence
} // namespace current
#endif // BLOCKS_PERSISTENCE_FILE_H
diff --git a/blocks/persistence/memory.h b/blocks/persistence/memory.h
index 735a58619..a7c45fa4f 100644
--- a/blocks/persistence/memory.h
+++ b/blocks/persistence/memory.h
@@ -334,12 +334,12 @@ class MemoryPersister {
Owned container_; // `Owned`, as iterators borrow it.
};
-} // namespace current::persistence::impl
+} // namespace impl
template
using Memory = ss::EntryPersister, ENTRY>;
-} // namespace current::persistence
+} // namespace persistence
} // namespace current
#endif // BLOCKS_PERSISTENCE_MEMORY_H
diff --git a/blocks/persistence/test.cc b/blocks/persistence/test.cc
index e781c1bda..9e19dde81 100644
--- a/blocks/persistence/test.cc
+++ b/blocks/persistence/test.cc
@@ -845,21 +845,18 @@ void IteratorPerformanceTest(IMPL& impl, bool publish = true) {
EXPECT_EQ(10ull, (*impl.Iterate(10, 11).begin()).idx_ts.index);
EXPECT_EQ(10000ll, (*impl.Iterate(10, 11).begin()).idx_ts.us.count());
EXPECT_EQ("0000010 kkkkkk", (*impl.Iterate(10, 11).begin()).entry.s);
- EXPECT_EQ("{\"index\":10,\"us\":10000}\t{\"s\":\"0000010 kkkkkk\"}",
- (*impl.IterateUnsafe(10, 11).begin()));
+ EXPECT_EQ("{\"index\":10,\"us\":10000}\t{\"s\":\"0000010 kkkkkk\"}", (*impl.IterateUnsafe(10, 11).begin()));
EXPECT_EQ(100ull, (*impl.Iterate(100, 101).begin()).idx_ts.index);
EXPECT_EQ(100000ll, (*impl.Iterate(100, 101).begin()).idx_ts.us.count());
EXPECT_EQ("0000100 wwwww", (*impl.Iterate(100, 101).begin()).entry.s);
- EXPECT_EQ("{\"index\":100,\"us\":100000}\t{\"s\":\"0000100 wwwww\"}",
- (*impl.IterateUnsafe(100, 101).begin()));
+ EXPECT_EQ("{\"index\":100,\"us\":100000}\t{\"s\":\"0000100 wwwww\"}", (*impl.IterateUnsafe(100, 101).begin()));
}
{
// By timestamp.
EXPECT_EQ(0ull, (*impl.Iterate(us_t(0), us_t(1000)).begin()).idx_ts.index);
EXPECT_EQ(0ll, (*impl.Iterate(us_t(0), us_t(1000)).begin()).idx_ts.us.count());
EXPECT_EQ("0000000 aaa", (*impl.Iterate(us_t(0), us_t(1000)).begin()).entry.s);
- EXPECT_EQ("{\"index\":0,\"us\":0}\t{\"s\":\"0000000 aaa\"}",
- (*impl.IterateUnsafe(us_t(0), us_t(1000)).begin()));
+ EXPECT_EQ("{\"index\":0,\"us\":0}\t{\"s\":\"0000000 aaa\"}", (*impl.IterateUnsafe(us_t(0), us_t(1000)).begin()));
EXPECT_EQ(10ull, (*impl.Iterate(us_t(10000), us_t(11000)).begin()).idx_ts.index);
EXPECT_EQ(10000ll, (*impl.Iterate(us_t(10000), us_t(11000)).begin()).idx_ts.us.count());
EXPECT_EQ("0000010 kkkkkk", (*impl.Iterate(us_t(10000), us_t(11000)).begin()).entry.s);
@@ -990,10 +987,10 @@ TEST(PersistenceLayer, FileIteratorCanNotOutliveFile) {
TEST(PersistenceLayer, Exceptions) {
using namespace persistence_test;
using IMPL = current::persistence::File;
- using current::ss::IndexAndTimestamp;
- using current::ss::InconsistentTimestampException;
- using current::ss::InconsistentIndexException;
using current::persistence::MalformedEntryException;
+ using current::ss::InconsistentIndexException;
+ using current::ss::InconsistentTimestampException;
+ using current::ss::IndexAndTimestamp;
const auto namespace_name = current::ss::StreamNamespaceName("namespace", "entry_name");
const std::string persistence_file_name = current::FileSystem::JoinPath(FLAGS_persistence_test_tmpdir, "data");
diff --git a/blocks/self_modifying_config/test.cc b/blocks/self_modifying_config/test.cc
index bc8fdc62b..a1ab04c31 100644
--- a/blocks/self_modifying_config/test.cc
+++ b/blocks/self_modifying_config/test.cc
@@ -88,8 +88,9 @@ TEST(SelfModifyingConfig, ReadFileException) {
current::time::SetNow(
current::IMFFixDateTimeStringToTimestamp("Tue, 16 Aug 1983 00:00:00 GMT")); // I was born. -- D.K.
- ASSERT_THROW(static_cast(std::make_unique>(config_filename)),
- current::SelfModifyingConfigReadFileException);
+ ASSERT_THROW(
+ static_cast(std::make_unique>(config_filename)),
+ current::SelfModifyingConfigReadFileException);
try {
static_cast(std::make_unique>(config_filename));
} catch (const current::SelfModifyingConfigReadFileException& e) {
@@ -115,8 +116,9 @@ TEST(SelfModifyingConfig, ParseJSONException) {
current::FileSystem::WriteStringToFile("De Louboutin.", config_filename.c_str());
- ASSERT_THROW(static_cast(std::make_unique>(config_filename)),
- current::SelfModifyingConfigParseJSONException);
+ ASSERT_THROW(
+ static_cast(std::make_unique>(config_filename)),
+ current::SelfModifyingConfigParseJSONException);
try {
static_cast(std::make_unique>(config_filename));
} catch (const current::SelfModifyingConfigParseJSONException& e) {
@@ -144,8 +146,9 @@ TEST(SelfModifyingConfig, WriteFileException) {
current::FileSystem::WriteStringToFile(JSON(UnitTestSelfModifyingConfig(4)), config_filename.c_str());
- ASSERT_THROW(static_cast(std::make_unique>(config_filename)),
- current::SelfModifyingConfigWriteFileException);
+ ASSERT_THROW(
+ static_cast(std::make_unique>(config_filename)),
+ current::SelfModifyingConfigWriteFileException);
try {
static_cast(std::make_unique>(config_filename));
} catch (const current::SelfModifyingConfigWriteFileException& e) {
diff --git a/blocks/ss/exceptions.h b/blocks/ss/exceptions.h
index a05da964e..e17bd587d 100644
--- a/blocks/ss/exceptions.h
+++ b/blocks/ss/exceptions.h
@@ -52,7 +52,7 @@ struct InconsistentTimestampException : InconsistentIndexOrTimestampException {
static_cast(found.count()))) {}
};
-} // namespace current::ss
+} // namespace ss
} // namespace current
#endif // BLOCKS_SS_EXCEPTIONS_H
diff --git a/blocks/ss/idx_ts.h b/blocks/ss/idx_ts.h
index 9a9773100..ac87258bc 100644
--- a/blocks/ss/idx_ts.h
+++ b/blocks/ss/idx_ts.h
@@ -81,12 +81,12 @@ CURRENT_STRUCT(HeadAndOptionalIndexAndTimestamp) {
CURRENT_USE_FIELD_AS_TIMESTAMP(head);
CURRENT_DEFAULT_CONSTRUCTOR(HeadAndOptionalIndexAndTimestamp) : head(0) {}
CURRENT_CONSTRUCTOR(HeadAndOptionalIndexAndTimestamp)(std::chrono::microseconds head) : head(head) {}
- CURRENT_CONSTRUCTOR(HeadAndOptionalIndexAndTimestamp)(std::chrono::microseconds head, IndexAndTimestamp idxts)
- : head(head), idxts(idxts) {
+ CURRENT_CONSTRUCTOR(HeadAndOptionalIndexAndTimestamp)
+ (std::chrono::microseconds head, IndexAndTimestamp idxts) : head(head), idxts(idxts) {
CURRENT_ASSERT(head >= idxts.us);
}
- CURRENT_CONSTRUCTOR(HeadAndOptionalIndexAndTimestamp)(
- std::chrono::microseconds head, uint64_t index, std::chrono::microseconds us)
+ CURRENT_CONSTRUCTOR(HeadAndOptionalIndexAndTimestamp)
+ (std::chrono::microseconds head, uint64_t index, std::chrono::microseconds us)
: head(head), idxts(IndexAndTimestamp(index, us)) {
#ifndef CURRENT_BUILD_WITH_PARANOIC_RUNTIME_CHECKS
CURRENT_ASSERT(head >= us);
@@ -99,7 +99,7 @@ CURRENT_STRUCT(HeadAndOptionalIndexAndTimestamp) {
}
};
-} // namespace current::ss
+} // namespace ss
} // namespace current
using idxts_t = current::ss::IndexAndTimestamp;
diff --git a/blocks/ss/persister.h b/blocks/ss/persister.h
index f1610abdc..4eb4a69c6 100644
--- a/blocks/ss/persister.h
+++ b/blocks/ss/persister.h
@@ -53,8 +53,7 @@ class EntryPersister : public GenericEntryPersister, public IMPL {
using IterableRangeUnsafe = typename IMPL::IterableRangeUnsafe;
template
- explicit EntryPersister(std::mutex& mutex, ARGS&&... args)
- : IMPL(mutex, std::forward(args)...) {}
+ explicit EntryPersister(std::mutex& mutex, ARGS&&... args) : IMPL(mutex, std::forward(args)...) {}
virtual ~EntryPersister() {}
template , T>;
};
-} // namespace current::ss
+} // namespace ss
} // namespace current
#endif // BLOCKS_SS_PERSISTER_H
diff --git a/blocks/ss/pubsub.h b/blocks/ss/pubsub.h
index 9426082ed..da250a47e 100644
--- a/blocks/ss/pubsub.h
+++ b/blocks/ss/pubsub.h
@@ -52,8 +52,7 @@ class EntryPublisher : public GenericEntryPublisher, public IMPL {
public:
template
- explicit EntryPublisher(ARGS&&... args)
- : IMPL(std::forward(args)...) {}
+ explicit EntryPublisher(ARGS&&... args) : IMPL(std::forward(args)...) {}
virtual ~EntryPublisher() {}
@@ -133,8 +132,7 @@ template
class EntrySubscriber : public GenericEntrySubscriber, public IMPL {
public:
template
- EntrySubscriber(ARGS&&... args)
- : IMPL(std::forward(args)...) {}
+ EntrySubscriber(ARGS&&... args) : IMPL(std::forward(args)...) {}
virtual ~EntrySubscriber() {}
EntryResponse operator()(const ENTRY& e, idxts_t current, idxts_t last) { return IMPL::operator()(e, current, last); }
@@ -211,7 +209,7 @@ struct PassEntryToSubscriberIfTypeMatchesImpl {
}
};
-} // namespace current::ss::impl
+} // namespace impl
template
EntryResponse PassEntryToSubscriberIfTypeMatches(F&& f, G&& fallback, E&& entry, idxts_t current, idxts_t last) {
@@ -219,7 +217,7 @@ EntryResponse PassEntryToSubscriberIfTypeMatches(F&& f, G&& fallback, E&& entry,
std::forward(f), std::forward(fallback), std::forward(entry), current, last);
}
-} // namespace current::ss
+} // namespace ss
} // namespace current
#endif // BLOCKS_SS_PUBSUB_H
diff --git a/blocks/ss/signature.h b/blocks/ss/signature.h
index 75d713fa4..44dc620da 100644
--- a/blocks/ss/signature.h
+++ b/blocks/ss/signature.h
@@ -35,17 +35,19 @@ CURRENT_STRUCT(StreamNamespaceName) {
CURRENT_FIELD(namespace_name, std::string);
CURRENT_FIELD(entry_name, std::string);
CURRENT_DEFAULT_CONSTRUCTOR(StreamNamespaceName) {}
- CURRENT_CONSTRUCTOR(StreamNamespaceName)(const std::string& namespace_name, const std::string& entry_name)
+ CURRENT_CONSTRUCTOR(StreamNamespaceName)
+ (const std::string& namespace_name, const std::string& entry_name)
: namespace_name(namespace_name), entry_name(entry_name) {}
};
CURRENT_STRUCT(StreamSignature, StreamNamespaceName) {
CURRENT_FIELD(schema, reflection::SchemaInfo);
CURRENT_DEFAULT_CONSTRUCTOR(StreamSignature) {}
- CURRENT_CONSTRUCTOR(StreamSignature)(
- const std::string& namespace_name, const std::string& entry_name, const reflection::SchemaInfo& schema)
+ CURRENT_CONSTRUCTOR(StreamSignature)
+ (const std::string& namespace_name, const std::string& entry_name, const reflection::SchemaInfo& schema)
: SUPER(namespace_name, entry_name), schema(schema) {}
- CURRENT_CONSTRUCTOR(StreamSignature)(const StreamNamespaceName& namespace_name, const reflection::SchemaInfo& schema)
+ CURRENT_CONSTRUCTOR(StreamSignature)
+ (const StreamNamespaceName& namespace_name, const reflection::SchemaInfo& schema)
: SUPER(namespace_name), schema(std::move(schema)) {}
};
diff --git a/blocks/ss/types.h b/blocks/ss/types.h
index bafb0184c..413b92666 100644
--- a/blocks/ss/types.h
+++ b/blocks/ss/types.h
@@ -37,10 +37,9 @@ template
#ifndef CURRENT_FOR_CPP14
inline
#endif // CURRENT_FOR_CPP14
-constexpr
-bool can_publish_v = std::is_constructible_v;
+ constexpr bool can_publish_v = std::is_constructible_v;
-} // namespace current::ss
+} // namespace ss
} // namespace current
#endif // BLOCKS_SS_TYPES_H
diff --git a/blocks/url/exceptions.h b/blocks/url/exceptions.h
index 15e66ee27..887e99544 100644
--- a/blocks/url/exceptions.h
+++ b/blocks/url/exceptions.h
@@ -64,7 +64,7 @@ struct URLParseSpecificObjectAsURLParameterException : URLParseObjectAsURLParame
: URLParseObjectAsURLParameterException(key, error, DescribeT()) {}
};
-} // namespace current::url
+} // namespace url
} // namespace current
#endif // BLOCKS_URL_EXCEPTIONS_H
diff --git a/blocks/url/url.h b/blocks/url/url.h
index 59ba6eacf..4ca959da7 100644
--- a/blocks/url/url.h
+++ b/blocks/url/url.h
@@ -72,7 +72,7 @@ namespace impl {
namespace {
const char* const kDefaultScheme = "http";
const char* const kDefaultHost = "localhost";
-}
+} // namespace
struct URLWithoutParametersParser {
std::string host = "";
@@ -318,7 +318,8 @@ struct URLParametersExtractor {
using super_t = current::reflection::SuperType;
FillObjectImpl::DoIt(parameters, static_cast(object));
QueryParametersObjectFiller parser{parameters};
- current::reflection::VisitAllFields::WithObject(object, parser);
+ current::reflection::VisitAllFields::WithObject(object,
+ parser);
}
};
@@ -475,10 +476,9 @@ struct URL : URLParametersExtractor, URLWithoutParametersParser {
static bool IsPathValidToRegister(const std::string& path) {
const std::set valid_nonalnum_chars{
'/', '-', '.', '_', '~', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@'};
- return find_if(path.begin(),
- path.end(),
- [&valid_nonalnum_chars](char c) { return !(isalnum(c) || valid_nonalnum_chars.count(c)); }) ==
- path.end();
+ return find_if(path.begin(), path.end(), [&valid_nonalnum_chars](char c) {
+ return !(isalnum(c) || valid_nonalnum_chars.count(c));
+ }) == path.end();
}
};
diff --git a/blocks/xterm/example.cc b/blocks/xterm/example.cc
index b73e494fa..e86f70746 100644
--- a/blocks/xterm/example.cc
+++ b/blocks/xterm/example.cc
@@ -19,8 +19,7 @@ int main(int argc, char** argv) {
// Basic VT100 demo.
using namespace current::vt100;
- std::cout << "Default, " << bold << "bold" << normal << ", " << dim << "dim" << normal << ", done."
- << std::endl;
+ std::cout << "Default, " << bold << "bold" << normal << ", " << dim << "dim" << normal << ", done." << std::endl;
#ifndef CURRENT_WINDOWS
std::cout << "Default, " << italic << "italic" << noitalic << '.' << std::endl;
#endif // CURRENT_WINDOWS
@@ -48,10 +47,9 @@ int main(int argc, char** argv) {
std::cout << "Default, " << background(red) << blue << bold << "blue on red " << reverse << " reversed "
<< noreverse << " back to blue on red" << reset << '.' << std::endl;
- std::cout << "Default, " << strikeout << "no " << red << "red" << bold << " bold" << italic << " italic"
- << noitalic << ' ' << underlined << "underlined" << nounderlined << ' ' << doubleunderlined
- << "doubleunderlined" << nounderlined << normal << default_color << " style" << nostrikeout
- << '.' << reset << std::endl;
+ std::cout << "Default, " << strikeout << "no " << red << "red" << bold << " bold" << italic << " italic" << noitalic
+ << ' ' << underlined << "underlined" << nounderlined << ' ' << doubleunderlined << "doubleunderlined"
+ << nounderlined << normal << default_color << " style" << nostrikeout << '.' << reset << std::endl;
}
{
@@ -86,7 +84,7 @@ int main(int argc, char** argv) {
}
std::cout << "Done." << std::endl;
}
- #endif
+#endif
if (false) {
// NOTE(dkorolev): This fails on my Linux. :/ Prints `Test3> tttesting ... OK`, then `Test3> ttDone.` at the end.
diff --git a/blocks/xterm/multiline.cc b/blocks/xterm/multiline.cc
index d3d723bdc..d4c8d1faa 100644
--- a/blocks/xterm/multiline.cc
+++ b/blocks/xterm/multiline.cc
@@ -11,18 +11,22 @@ int main() {
std::vector threads;
int index = 0u;
do {
- threads.emplace_back([&multiline_progress](int index) {
- current::ProgressLine line = multiline_progress();
- const double k = current::random::RandomDouble(0.01, 0.04);
- const double b = current::random::RandomDouble(0.0, 6.28);
- const double a = current::random::RandomDouble(20, 45);
- const auto t0 = current::time::Now();
- while (true) {
- line << "Line" << index << ": " << std::string(static_cast(
- 0.5 * (std::sin((current::time::Now() - t0).count() * 1e-3 * k + b) + 1.0) * a), '*');
- std::this_thread::sleep_for(std::chrono::milliseconds(current::random::RandomInt(1, 25)));
- }
- }, ++index);
+ threads.emplace_back(
+ [&multiline_progress](int index) {
+ current::ProgressLine line = multiline_progress();
+ const double k = current::random::RandomDouble(0.01, 0.04);
+ const double b = current::random::RandomDouble(0.0, 6.28);
+ const double a = current::random::RandomDouble(20, 45);
+ const auto t0 = current::time::Now();
+ while (true) {
+ line << "Line" << index << ": "
+ << std::string(static_cast(
+ 0.5 * (std::sin((current::time::Now() - t0).count() * 1e-3 * k + b) + 1.0) * a),
+ '*');
+ std::this_thread::sleep_for(std::chrono::milliseconds(current::random::RandomInt(1, 25)));
+ }
+ },
+ ++index);
std::this_thread::sleep_for(std::chrono::milliseconds(current::random::RandomInt(500, 2500 * index)));
} while (true);
}
diff --git a/blocks/xterm/progress.h b/blocks/xterm/progress.h
index a59cf526b..f76bb603b 100644
--- a/blocks/xterm/progress.h
+++ b/blocks/xterm/progress.h
@@ -64,7 +64,8 @@ class ProgressLine final {
ProgressLine(DoConstruct,
std::ostream& os = std::cout,
std::function up = nullptr,
- std::mutex* maybe_mutex = nullptr) : os_(os), up_(up), maybe_mutex_(maybe_mutex) {
+ std::mutex* maybe_mutex = nullptr)
+ : os_(os), up_(up), maybe_mutex_(maybe_mutex) {
if (up_) {
// Move to the next line right away to "allocate" a new line for this "multiline" "progress instance".
const auto maybe_lock = MaybeLock();
@@ -128,9 +129,7 @@ class ProgressLine final {
return status;
}
- std::string GetUndecoratedString() const {
- return current_undecorated_status_;
- }
+ std::string GetUndecoratedString() const { return current_undecorated_status_; }
protected:
void DoUpdate(Status& status) {
@@ -139,7 +138,7 @@ class ProgressLine final {
if (new_status != current_status_) {
const size_t new_status_length =
- current::strings::UTF8StringLength(status.oss_text_with_no_vt100_escape_sequences.str());
+ current::strings::UTF8StringLength(status.oss_text_with_no_vt100_escape_sequences.str());
if (!up_) {
const auto maybe_lock = MaybeLock();
DoClearString(os_);
@@ -153,8 +152,8 @@ class ProgressLine final {
os_ << vt100::up(n + 1) << new_status << vt100::reset << '\n' << vt100::down(n) << std::flush;
} else {
const size_t d = current_status_length_ - new_status_length;
- os_ << vt100::up(n + 1) << new_status << vt100::reset
- << std::string(d, ' ') << '\n' << vt100::down(n) << std::flush;
+ os_ << vt100::up(n + 1) << new_status << vt100::reset << std::string(d, ' ') << '\n'
+ << vt100::down(n) << std::flush;
}
}
current_status_ = new_status;
@@ -172,7 +171,8 @@ class MultilineProgress final {
current::ProgressLine operator()(std::ostream& os = std::cout) {
++total_;
int index = total_;
- return current::ProgressLine(os, [index, this]() { return total_ - index; }, mutex_);
+ return current::ProgressLine(
+ os, [index, this]() { return total_ - index; }, mutex_);
}
};
diff --git a/blocks/xterm/vt100.h b/blocks/xterm/vt100.h
index e0b0374a1..a02cc9083 100644
--- a/blocks/xterm/vt100.h
+++ b/blocks/xterm/vt100.h
@@ -102,15 +102,11 @@ struct UD final {
explicit UD(int by) : down(by) {}
};
-inline UD up(int d) {
- return UD(-d);
-}
+inline UD up(int d) { return UD(-d); }
-inline UD down(int d) {
- return UD(+d);
-}
+inline UD down(int d) { return UD(+d); }
-} // namespace current::vt100
+} // namespace vt100
} // namespace current
inline void EnableVirtualTerminalProcessing() {
diff --git a/bricks/c++17/test.cc b/bricks/c++17/test.cc
index f3ca48387..f44f8978d 100644
--- a/bricks/c++17/test.cc
+++ b/bricks/c++17/test.cc
@@ -28,7 +28,9 @@ SOFTWARE.
#if __cplusplus >= 201703L
TEST(CPlusPlus17, Enabled) {
- auto const generic_lambda = [](auto const x) { return current::reflection::TypeName>(); };
+ auto const generic_lambda = [](auto const x) {
+ return current::reflection::TypeName>();
+ };
EXPECT_STREQ("uint32_t", generic_lambda(static_cast(42)));
EXPECT_STREQ("bool", generic_lambda(true));
diff --git a/bricks/dflags/test.cc b/bricks/dflags/test.cc
index 732278bed..1c7e7bcbd 100644
--- a/bricks/dflags/test.cc
+++ b/bricks/dflags/test.cc
@@ -276,17 +276,17 @@ TEST(DFlags, PrintsHelpDeathTest) {
char p2[] = "--help";
char* pp[] = {p1, p2};
char** argv = pp;
- EXPECT_DEATH(ParseDFlags(&argc, &argv), DFLAGS_TEST_REGEX(
- "3 flags registered.\n"
- "\t--bar , bool\n"
- "\t\tBar\\.\n"
- "\t\tDefault value\\: True\n"
- "\t--foo , std\\:\\:string\n"
- "\t\tFoo\\.\n"
- "\t\tDefault value: 'TRUE THIS'\n"
- "\t--meh , int32_t\n"
- "\t\tMeh\\.\n"
- "\t\tDefault value: 42\n"));
+ EXPECT_DEATH(ParseDFlags(&argc, &argv),
+ DFLAGS_TEST_REGEX("3 flags registered.\n"
+ "\t--bar , bool\n"
+ "\t\tBar\\.\n"
+ "\t\tDefault value\\: True\n"
+ "\t--foo , std\\:\\:string\n"
+ "\t\tFoo\\.\n"
+ "\t\tDefault value: 'TRUE THIS'\n"
+ "\t--meh , int32_t\n"
+ "\t\tMeh\\.\n"
+ "\t\tDefault value: 42\n"));
}
TEST(DFlags, UndefinedFlagDeathTest) {
@@ -319,7 +319,8 @@ TEST(DFlags, TooManyDashesDeathTest) {
char p2[] = "---whatever42";
char* pp[] = {p1, p2};
char** argv = pp;
- EXPECT_DEATH(ParseDFlags(&argc, &argv), DFLAGS_TEST_REGEX("Parameter: '---whatever42' has too many dashes in front\\."));
+ EXPECT_DEATH(ParseDFlags(&argc, &argv),
+ DFLAGS_TEST_REGEX("Parameter: '---whatever42' has too many dashes in front\\."));
}
TEST(DFlags, NoValueDeathTest) {
diff --git a/bricks/dot/graphviz.h b/bricks/dot/graphviz.h
index a824b47a2..2b64e59d7 100644
--- a/bricks/dot/graphviz.h
+++ b/bricks/dot/graphviz.h
@@ -259,8 +259,8 @@ struct GenericGraph {
const auto output_file_deleter = current::FileSystem::ScopedRmFile(output_file_name);
current::FileSystem::WriteStringToFile(AsDOT(), input_file_name.c_str());
- CURRENT_ASSERT(!bricks::system::SystemCall(current::strings::Printf(
- "dot -T svg %s -o %s", input_file_name.c_str(), output_file_name.c_str()).c_str()));
+ CURRENT_ASSERT(!bricks::system::SystemCall(
+ current::strings::Printf("dot -T svg %s -o %s", input_file_name.c_str(), output_file_name.c_str()).c_str()));
return current::FileSystem::ReadFileAsString(output_file_name.c_str());
}
};
diff --git a/bricks/file/file.h b/bricks/file/file.h
index d3c832a5c..d93f7c8e0 100644
--- a/bricks/file/file.h
+++ b/bricks/file/file.h
@@ -326,26 +326,27 @@ struct FileSystem {
// Inner lambdas have distinct types thus creating template instantiation limit,
// which is fixed by casting the lambda to its canonical type.
ScanDirUntil(directory,
- static_cast>([&item_handler, parameters, &context](
- const ScanDirItemInfo& item_info) {
- const ScanDirParameters mask =
- item_info.is_directory ? ScanDirParameters::ListDirsOnly : ScanDirParameters::ListFilesOnly;
- if (static_cast(parameters) & static_cast(mask)) {
- if (!item_handler(item_info)) {
- return false;
- }
- }
- if (item_info.is_directory) {
- context.path_components.push_back(item_info.basename);
- const auto guard = current::MakeScopeGuard([&context]() { context.path_components.pop_back(); });
- ScanDirUntil(item_info.pathname,
- std::forward(item_handler),
- parameters,
- ScanDirRecursive::Yes,
- context);
- }
- return true;
- }),
+ static_cast>(
+ [&item_handler, parameters, &context](const ScanDirItemInfo& item_info) {
+ const ScanDirParameters mask = item_info.is_directory ? ScanDirParameters::ListDirsOnly
+ : ScanDirParameters::ListFilesOnly;
+ if (static_cast(parameters) & static_cast(mask)) {
+ if (!item_handler(item_info)) {
+ return false;
+ }
+ }
+ if (item_info.is_directory) {
+ context.path_components.push_back(item_info.basename);
+ const auto guard =
+ current::MakeScopeGuard([&context]() { context.path_components.pop_back(); });
+ ScanDirUntil(item_info.pathname,
+ std::forward(item_handler),
+ parameters,
+ ScanDirRecursive::Yes,
+ context);
+ }
+ return true;
+ }),
ScanDirParameters::ListFilesAndDirs,
ScanDirRecursive::No,
context);
@@ -357,13 +358,14 @@ struct FileSystem {
ITEM_HANDLER&& item_handler,
ScanDirParameters parameters = ScanDirParameters::ListFilesOnly,
ScanDirRecursive recursive = ScanDirRecursive::No) {
- ScanDirUntil(directory,
- [&item_handler](const ScanDirItemInfo& item_info) {
- item_handler(item_info);
- return true;
- },
- parameters,
- recursive);
+ ScanDirUntil(
+ directory,
+ [&item_handler](const ScanDirItemInfo& item_info) {
+ item_handler(item_info);
+ return true;
+ },
+ parameters,
+ recursive);
}
enum class RmFileParameters { ThrowExceptionOnError, Silent };
@@ -416,18 +418,18 @@ struct FileSystem {
}
} else {
try {
- ScanDir(directory,
- [parameters](const ScanDirItemInfo& item_info) {
- if (item_info.is_directory) {
- RmDir(item_info.pathname, parameters, RmDirRecursive::Yes);
- } else {
- RmFile(item_info.pathname,
- (parameters == RmDirParameters::ThrowExceptionOnError)
- ? RmFileParameters::ThrowExceptionOnError
- : RmFileParameters::Silent);
- }
- },
- ScanDirParameters::ListFilesAndDirs);
+ ScanDir(
+ directory,
+ [parameters](const ScanDirItemInfo& item_info) {
+ if (item_info.is_directory) {
+ RmDir(item_info.pathname, parameters, RmDirRecursive::Yes);
+ } else {
+ RmFile(item_info.pathname,
+ (parameters == RmDirParameters::ThrowExceptionOnError) ? RmFileParameters::ThrowExceptionOnError
+ : RmFileParameters::Silent);
+ }
+ },
+ ScanDirParameters::ListFilesAndDirs);
RmDir(directory, parameters, RmDirRecursive::No);
} catch (const current::Exception&) {
if (parameters == RmDirParameters::ThrowExceptionOnError) {
diff --git a/bricks/file/test.cc b/bricks/file/test.cc
index f81b2c33a..a5dc215d3 100644
--- a/bricks/file/test.cc
+++ b/bricks/file/test.cc
@@ -33,11 +33,11 @@ SOFTWARE.
#include "../strings/join.h"
#include "../../3rdparty/gtest/gtest-main-with-dflags.h"
-using current::FileSystem;
-using current::FileException;
using current::DirDoesNotExistException;
-using current::PathNotDirException;
using current::DirNotEmptyException;
+using current::FileException;
+using current::FileSystem;
+using current::PathNotDirException;
DEFINE_string(file_test_tmpdir, ".current", "Local path for the test to create temporary files in.");
@@ -302,11 +302,10 @@ TEST(File, ScanDirParameters) {
{
std::set names;
std::map item_infos;
- FileSystem::ScanDir(base_dir,
- [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) {
- names.insert(x.basename);
- item_infos.insert(std::make_pair(x.basename, x));
- });
+ FileSystem::ScanDir(base_dir, [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) {
+ names.insert(x.basename);
+ item_infos.insert(std::make_pair(x.basename, x));
+ });
EXPECT_EQ("f", current::strings::Join(names, ','));
EXPECT_EQ(f, item_infos.at("f").pathname);
EXPECT_EQ(base_dir, item_infos.at("f").dirname);
@@ -316,12 +315,13 @@ TEST(File, ScanDirParameters) {
{
std::set names;
std::map item_infos;
- FileSystem::ScanDir(base_dir,
- [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) {
- names.insert(x.basename);
- item_infos.insert(std::make_pair(x.basename, x));
- },
- FileSystem::ScanDirParameters::ListFilesOnly);
+ FileSystem::ScanDir(
+ base_dir,
+ [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) {
+ names.insert(x.basename);
+ item_infos.insert(std::make_pair(x.basename, x));
+ },
+ FileSystem::ScanDirParameters::ListFilesOnly);
EXPECT_EQ("f", current::strings::Join(names, ','));
EXPECT_EQ(f, item_infos.at("f").pathname);
EXPECT_EQ(base_dir, item_infos.at("f").dirname);
@@ -331,12 +331,13 @@ TEST(File, ScanDirParameters) {
{
std::set names;
std::map item_infos;
- FileSystem::ScanDir(base_dir,
- [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) {
- names.insert(x.basename);
- item_infos.insert(std::make_pair(x.basename, x));
- },
- FileSystem::ScanDirParameters::ListDirsOnly);
+ FileSystem::ScanDir(
+ base_dir,
+ [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) {
+ names.insert(x.basename);
+ item_infos.insert(std::make_pair(x.basename, x));
+ },
+ FileSystem::ScanDirParameters::ListDirsOnly);
EXPECT_EQ("d", current::strings::Join(names, ','));
EXPECT_EQ(d, item_infos.at("d").pathname);
EXPECT_EQ(base_dir, item_infos.at("d").dirname);
@@ -346,12 +347,13 @@ TEST(File, ScanDirParameters) {
{
std::set names;
std::map item_infos;
- FileSystem::ScanDir(base_dir,
- [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) {
- names.insert(x.basename);
- item_infos.insert(std::make_pair(x.basename, x));
- },
- FileSystem::ScanDirParameters::ListFilesAndDirs);
+ FileSystem::ScanDir(
+ base_dir,
+ [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) {
+ names.insert(x.basename);
+ item_infos.insert(std::make_pair(x.basename, x));
+ },
+ FileSystem::ScanDirParameters::ListFilesAndDirs);
EXPECT_EQ("d,f", current::strings::Join(names, ','));
EXPECT_EQ(d, item_infos.at("d").pathname);
EXPECT_EQ(base_dir, item_infos.at("d").dirname);
@@ -388,13 +390,14 @@ TEST(File, ScanDirRecursive) {
std::set basenames;
std::map item_infos;
- FileSystem::ScanDir(base_dir,
- [&basenames, &item_infos](const FileSystem::ScanDirItemInfo& x) {
- basenames.insert(x.basename);
- item_infos.insert(std::make_pair(x.basename, x));
- },
- FileSystem::ScanDirParameters::ListFilesOnly,
- FileSystem::ScanDirRecursive::Yes);
+ FileSystem::ScanDir(
+ base_dir,
+ [&basenames, &item_infos](const FileSystem::ScanDirItemInfo& x) {
+ basenames.insert(x.basename);
+ item_infos.insert(std::make_pair(x.basename, x));
+ },
+ FileSystem::ScanDirParameters::ListFilesOnly,
+ FileSystem::ScanDirRecursive::Yes);
EXPECT_EQ("base_dir_file,sub_dir_file,sub_sub_dir_file,sub_sub_dir_file_2", current::strings::Join(basenames, ','));
@@ -413,13 +416,14 @@ TEST(File, ScanDirRecursive) {
std::set basenames;
std::map item_infos;
- FileSystem::ScanDir(base_dir,
- [&basenames, &item_infos](const FileSystem::ScanDirItemInfo& x) {
- basenames.insert(x.basename);
- item_infos.insert(std::make_pair(x.basename, x));
- },
- FileSystem::ScanDirParameters::ListDirsOnly,
- FileSystem::ScanDirRecursive::Yes);
+ FileSystem::ScanDir(
+ base_dir,
+ [&basenames, &item_infos](const FileSystem::ScanDirItemInfo& x) {
+ basenames.insert(x.basename);
+ item_infos.insert(std::make_pair(x.basename, x));
+ },
+ FileSystem::ScanDirParameters::ListDirsOnly,
+ FileSystem::ScanDirRecursive::Yes);
EXPECT_EQ("sub_dir,sub_sub_dir,sub_sub_dir_2", current::strings::Join(basenames, ','));
@@ -436,13 +440,14 @@ TEST(File, ScanDirRecursive) {
std::set basenames;
std::map item_infos;
- FileSystem::ScanDir(base_dir,
- [&basenames, &item_infos](const FileSystem::ScanDirItemInfo& x) {
- basenames.insert(x.basename);
- item_infos.insert(std::make_pair(x.basename, x));
- },
- FileSystem::ScanDirParameters::ListFilesAndDirs,
- FileSystem::ScanDirRecursive::Yes);
+ FileSystem::ScanDir(
+ base_dir,
+ [&basenames, &item_infos](const FileSystem::ScanDirItemInfo& x) {
+ basenames.insert(x.basename);
+ item_infos.insert(std::make_pair(x.basename, x));
+ },
+ FileSystem::ScanDirParameters::ListFilesAndDirs,
+ FileSystem::ScanDirRecursive::Yes);
EXPECT_EQ("base_dir_file,sub_dir,sub_dir_file,sub_sub_dir,sub_sub_dir_2,sub_sub_dir_file,sub_sub_dir_file_2",
current::strings::Join(basenames, ','));
diff --git a/bricks/graph/gnuplot.h b/bricks/graph/gnuplot.h
index b85ecfd69..8cc9f3f8d 100644
--- a/bricks/graph/gnuplot.h
+++ b/bricks/graph/gnuplot.h
@@ -236,7 +236,7 @@ struct GNUPlot {
}
if (output_format_ != "gnuplot") {
CURRENT_ASSERT(!bricks::system::SystemCall(
- strings::Printf("gnuplot <%s >%s", input_file_name.c_str(), output_file_name.c_str())));
+ strings::Printf("gnuplot <%s >%s", input_file_name.c_str(), output_file_name.c_str())));
return current::FileSystem::ReadFileAsString(output_file_name.c_str());
} else {
// For unit tests, just compare the inputs.
diff --git a/bricks/net/http/headers/headers.h b/bricks/net/http/headers/headers.h
index 6a310384b..dff875a94 100644
--- a/bricks/net/http/headers/headers.h
+++ b/bricks/net/http/headers/headers.h
@@ -193,9 +193,9 @@ struct Headers final {
Headers(const std::string& header, const std::string& value) { Set(header, value); }
Headers(std::initializer_list> initializer) {
- std::for_each(initializer.begin(),
- initializer.end(),
- [this](const std::pair& h) { Set(h.first, h.second); });
+ std::for_each(initializer.begin(), initializer.end(), [this](const std::pair& h) {
+ Set(h.first, h.second);
+ });
}
// An instance of `Headers` can `Set()` / `Get()` / `Has()` / `Remove()` headers.
diff --git a/bricks/net/http/test.cc b/bricks/net/http/test.cc
index 921a9163c..489ce1894 100644
--- a/bricks/net/http/test.cc
+++ b/bricks/net/http/test.cc
@@ -37,19 +37,19 @@ SOFTWARE.
#include "../../../3rdparty/gtest/gtest-main-with-dflags.h"
-using current::net::Socket;
+using current::net::AttemptedToSendHTTPResponseMoreThanOnce;
+using current::net::ChunkSizeNotAValidHEXValue;
using current::net::ClientSocket;
using current::net::Connection;
-using current::net::HTTPServerConnection;
+using current::net::ConnectionResetByPeer;
+using current::net::DefaultInternalServerErrorMessage;
+using current::net::GetFileMimeType;
using current::net::HTTPRequestData;
-using current::net::HTTPResponseCodeValue;
using current::net::HTTPResponseCodeAsString;
-using current::net::GetFileMimeType;
-using current::net::DefaultInternalServerErrorMessage;
+using current::net::HTTPResponseCodeValue;
+using current::net::HTTPServerConnection;
+using current::net::Socket;
using current::net::SocketException;
-using current::net::ConnectionResetByPeer;
-using current::net::ChunkSizeNotAValidHEXValue;
-using current::net::AttemptedToSendHTTPResponseMoreThanOnce;
static void ExpectToReceive(const std::string& golden, Connection& connection) {
std::vector response(golden.length());
@@ -71,16 +71,18 @@ CURRENT_STRUCT(HTTPTestObject) {
TEST(PosixHTTPServerTest, Smoke) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
- std::thread t([port](Socket s) {
- HTTPServerConnection c(s.Accept());
- EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip);
- EXPECT_EQ(port, c.LocalIPAndPort().port);
- EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip);
- EXPECT_LT(0, c.RemoteIPAndPort().port);
- EXPECT_EQ("POST", c.HTTPRequest().Method());
- EXPECT_EQ("/", c.HTTPRequest().RawPath());
- c.SendHTTPResponse("Data: " + c.HTTPRequest().Body());
- }, std::move(reserved_port));
+ std::thread t(
+ [port](Socket s) {
+ HTTPServerConnection c(s.Accept());
+ EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip);
+ EXPECT_EQ(port, c.LocalIPAndPort().port);
+ EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip);
+ EXPECT_LT(0, c.RemoteIPAndPort().port);
+ EXPECT_EQ("POST", c.HTTPRequest().Method());
+ EXPECT_EQ("/", c.HTTPRequest().RawPath());
+ c.SendHTTPResponse("Data: " + c.HTTPRequest().Body());
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
EXPECT_EQ("127.0.0.1", connection.LocalIPAndPort().ip);
EXPECT_LT(0, connection.LocalIPAndPort().port);
@@ -106,16 +108,18 @@ TEST(PosixHTTPServerTest, Smoke) {
TEST(PosixHTTPServerTest, SmokeWithTrailingSpaces) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
- std::thread t([port](Socket s) {
- HTTPServerConnection c(s.Accept());
- EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip);
- EXPECT_EQ(port, c.LocalIPAndPort().port);
- EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip);
- EXPECT_LT(0, c.RemoteIPAndPort().port);
- EXPECT_EQ("POST", c.HTTPRequest().Method());
- EXPECT_EQ("/", c.HTTPRequest().RawPath());
- c.SendHTTPResponse("Data: " + c.HTTPRequest().Body());
- }, std::move(reserved_port));
+ std::thread t(
+ [port](Socket s) {
+ HTTPServerConnection c(s.Accept());
+ EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip);
+ EXPECT_EQ(port, c.LocalIPAndPort().port);
+ EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip);
+ EXPECT_LT(0, c.RemoteIPAndPort().port);
+ EXPECT_EQ("POST", c.HTTPRequest().Method());
+ EXPECT_EQ("/", c.HTTPRequest().RawPath());
+ c.SendHTTPResponse("Data: " + c.HTTPRequest().Body());
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
EXPECT_EQ("127.0.0.1", connection.LocalIPAndPort().ip);
EXPECT_LT(0, connection.LocalIPAndPort().port);
@@ -141,12 +145,14 @@ TEST(PosixHTTPServerTest, SmokeWithTrailingSpaces) {
TEST(PosixHTTPServerTest, SmokeWithArray) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
- std::thread t([](Socket s) {
- HTTPServerConnection c(s.Accept());
- EXPECT_EQ("GET", c.HTTPRequest().Method());
- EXPECT_EQ("/vector_char", c.HTTPRequest().RawPath());
- c.SendHTTPResponse(std::vector({'S', 't', 'r', 'i', 'n', 'g'}));
- }, std::move(reserved_port));
+ std::thread t(
+ [](Socket s) {
+ HTTPServerConnection c(s.Accept());
+ EXPECT_EQ("GET", c.HTTPRequest().Method());
+ EXPECT_EQ("/vector_char", c.HTTPRequest().RawPath());
+ c.SendHTTPResponse(std::vector({'S', 't', 'r', 'i', 'n', 'g'}));
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
connection.BlockingWrite("GET /vector_char HTTP/1.1\r\n", true);
connection.BlockingWrite("Host: localhost\r\n", true);
@@ -166,12 +172,14 @@ TEST(PosixHTTPServerTest, SmokeWithArray) {
TEST(PosixHTTPServerTest, SmokeWithObject) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
- std::thread t([](Socket s) {
- HTTPServerConnection c(s.Accept());
- EXPECT_EQ("GET", c.HTTPRequest().Method());
- EXPECT_EQ("/test_object", c.HTTPRequest().RawPath());
- c.SendHTTPResponse(HTTPTestObject());
- }, std::move(reserved_port));
+ std::thread t(
+ [](Socket s) {
+ HTTPServerConnection c(s.Accept());
+ EXPECT_EQ("GET", c.HTTPRequest().Method());
+ EXPECT_EQ("/test_object", c.HTTPRequest().RawPath());
+ c.SendHTTPResponse(HTTPTestObject());
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
connection.BlockingWrite("GET /test_object HTTP/1.1\r\n", true);
connection.BlockingWrite("Host: localhost\r\n", true);
@@ -191,12 +199,14 @@ TEST(PosixHTTPServerTest, SmokeWithObject) {
TEST(PosixHTTPServerTest, SmokeWithObjectWithCORSHeader) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
- std::thread t([](Socket s) {
- HTTPServerConnection c(s.Accept());
- EXPECT_EQ("GET", c.HTTPRequest().Method());
- EXPECT_EQ("/test_object", c.HTTPRequest().RawPath());
- c.SendHTTPResponse(HTTPTestObject(), HTTPResponseCode.OK, current::net::http::Headers().SetCORSHeader());
- }, std::move(reserved_port));
+ std::thread t(
+ [](Socket s) {
+ HTTPServerConnection c(s.Accept());
+ EXPECT_EQ("GET", c.HTTPRequest().Method());
+ EXPECT_EQ("/test_object", c.HTTPRequest().RawPath());
+ c.SendHTTPResponse(HTTPTestObject(), HTTPResponseCode.OK, current::net::http::Headers().SetCORSHeader());
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
connection.BlockingWrite("GET /test_object HTTP/1.1\r\n", true);
connection.BlockingWrite("Host: localhost\r\n", true);
@@ -217,15 +227,17 @@ TEST(PosixHTTPServerTest, SmokeWithObjectWithCORSHeader) {
TEST(PosixHTTPServerTest, SmokeChunkedResponse) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
- std::thread t([](Socket s) {
- HTTPServerConnection c(s.Accept());
- EXPECT_EQ("GET", c.HTTPRequest().Method());
- EXPECT_EQ("/chunked", c.HTTPRequest().RawPath());
- auto r = c.SendChunkedHTTPResponse();
- r.Send("onetwothree");
- r.Send(std::vector({'f', 'o', 'o'}));
- r.Send(HTTPTestObject());
- }, std::move(reserved_port));
+ std::thread t(
+ [](Socket s) {
+ HTTPServerConnection c(s.Accept());
+ EXPECT_EQ("GET", c.HTTPRequest().Method());
+ EXPECT_EQ("/chunked", c.HTTPRequest().RawPath());
+ auto r = c.SendChunkedHTTPResponse();
+ r.Send("onetwothree");
+ r.Send(std::vector({'f', 'o', 'o'}));
+ r.Send(HTTPTestObject());
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
connection.BlockingWrite("GET /chunked HTTP/1.1\r\n", true);
connection.BlockingWrite("Host: localhost\r\n", true);
@@ -250,15 +262,17 @@ TEST(PosixHTTPServerTest, SmokeChunkedResponse) {
TEST(PosixHTTPServerTest, SmokeChunkedResponseWithCORSHeader) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
- std::thread t([](Socket s) {
- HTTPServerConnection c(s.Accept());
- EXPECT_EQ("GET", c.HTTPRequest().Method());
- EXPECT_EQ("/chunked", c.HTTPRequest().RawPath());
- auto r = c.SendChunkedHTTPResponse(HTTPResponseCode.OK, current::net::http::Headers().SetCORSHeader());
- r.Send("onetwothree");
- r.Send(std::vector({'f', 'o', 'o'}));
- r.Send(HTTPTestObject());
- }, std::move(reserved_port));
+ std::thread t(
+ [](Socket s) {
+ HTTPServerConnection c(s.Accept());
+ EXPECT_EQ("GET", c.HTTPRequest().Method());
+ EXPECT_EQ("/chunked", c.HTTPRequest().RawPath());
+ auto r = c.SendChunkedHTTPResponse(HTTPResponseCode.OK, current::net::http::Headers().SetCORSHeader());
+ r.Send("onetwothree");
+ r.Send(std::vector({'f', 'o', 'o'}));
+ r.Send(HTTPTestObject());
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
connection.BlockingWrite("GET /chunked HTTP/1.1\r\n", true);
connection.BlockingWrite("Host: localhost\r\n", true);
@@ -284,15 +298,17 @@ TEST(PosixHTTPServerTest, SmokeChunkedResponseWithCORSHeader) {
TEST(PosixHTTPServerTest, SmokeWithHeaders) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
- std::thread t([](Socket s) {
- HTTPServerConnection c(s.Accept());
- EXPECT_EQ("POST", c.HTTPRequest().Method());
- EXPECT_EQ("/header", c.HTTPRequest().RawPath());
- c.SendHTTPResponse("OK",
- HTTPResponseCode.OK,
- current::net::http::Headers({{"foo", "bar"}, {"baz", "meh"}}),
- "here_is_" + c.HTTPRequest().Body());
- }, std::move(reserved_port));
+ std::thread t(
+ [](Socket s) {
+ HTTPServerConnection c(s.Accept());
+ EXPECT_EQ("POST", c.HTTPRequest().Method());
+ EXPECT_EQ("/header", c.HTTPRequest().RawPath());
+ c.SendHTTPResponse("OK",
+ HTTPResponseCode.OK,
+ current::net::http::Headers({{"foo", "bar"}, {"baz", "meh"}}),
+ "here_is_" + c.HTTPRequest().Body());
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
connection.BlockingWrite("POST /header HTTP/1.1\r\n", true);
connection.BlockingWrite("Host: localhost\r\n", true);
@@ -316,16 +332,18 @@ TEST(PosixHTTPServerTest, SmokeWithHeaders) {
TEST(PosixHTTPServerTest, SmokeWithLowercaseContentLength) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
- std::thread t([port](Socket s) {
- HTTPServerConnection c(s.Accept());
- EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip);
- EXPECT_EQ(port, c.LocalIPAndPort().port);
- EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip);
- EXPECT_LT(0, c.RemoteIPAndPort().port);
- EXPECT_EQ("POST", c.HTTPRequest().Method());
- EXPECT_EQ("/", c.HTTPRequest().RawPath());
- c.SendHTTPResponse("Data: " + c.HTTPRequest().Body());
- }, std::move(reserved_port));
+ std::thread t(
+ [port](Socket s) {
+ HTTPServerConnection c(s.Accept());
+ EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip);
+ EXPECT_EQ(port, c.LocalIPAndPort().port);
+ EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip);
+ EXPECT_LT(0, c.RemoteIPAndPort().port);
+ EXPECT_EQ("POST", c.HTTPRequest().Method());
+ EXPECT_EQ("/", c.HTTPRequest().RawPath());
+ c.SendHTTPResponse("Data: " + c.HTTPRequest().Body());
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
EXPECT_EQ("127.0.0.1", connection.LocalIPAndPort().ip);
EXPECT_LT(0, connection.LocalIPAndPort().port);
@@ -350,13 +368,15 @@ TEST(PosixHTTPServerTest, SmokeWithLowercaseContentLength) {
TEST(PosixHTTPServerTest, SmokeWithMethodInHeader) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
- std::thread t([](Socket s) {
- HTTPServerConnection c(s.Accept());
- EXPECT_EQ("PATCH", c.HTTPRequest().Method());
- EXPECT_EQ("/ugly", c.HTTPRequest().RawPath());
- EXPECT_EQ("YES", c.HTTPRequest().Body());
- c.SendHTTPResponse("PASS");
- }, std::move(reserved_port));
+ std::thread t(
+ [](Socket s) {
+ HTTPServerConnection c(s.Accept());
+ EXPECT_EQ("PATCH", c.HTTPRequest().Method());
+ EXPECT_EQ("/ugly", c.HTTPRequest().RawPath());
+ EXPECT_EQ("YES", c.HTTPRequest().Body());
+ c.SendHTTPResponse("PASS");
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
connection.BlockingWrite("POST /ugly HTTP/1.1\r\n", true);
connection.BlockingWrite("Host: localhost\r\n", true);
@@ -379,13 +399,15 @@ TEST(PosixHTTPServerTest, SmokeWithMethodInHeader) {
TEST(PosixHTTPServerTest, SmokeWithLowercaseMethodInLowercaseHeader) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
- std::thread t([](Socket s) {
- HTTPServerConnection c(s.Accept());
- EXPECT_EQ("PATCH", c.HTTPRequest().Method());
- EXPECT_EQ("/ugly2", c.HTTPRequest().RawPath());
- EXPECT_EQ("yes", c.HTTPRequest().Body());
- c.SendHTTPResponse("Pass");
- }, std::move(reserved_port));
+ std::thread t(
+ [](Socket s) {
+ HTTPServerConnection c(s.Accept());
+ EXPECT_EQ("PATCH", c.HTTPRequest().Method());
+ EXPECT_EQ("/ugly2", c.HTTPRequest().RawPath());
+ EXPECT_EQ("yes", c.HTTPRequest().Body());
+ c.SendHTTPResponse("Pass");
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
connection.BlockingWrite("POST /ugly2 HTTP/1.1\r\n", true);
connection.BlockingWrite("Host: localhost\r\n", true);
@@ -409,14 +431,16 @@ TEST(PosixHTTPServerTest, SmokeNoBodyForPOST) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
std::atomic_bool thrown(false);
- std::thread t([&thrown](Socket s) {
- try {
- HTTPServerConnection c(s.Accept());
- ASSERT_TRUE(false);
- } catch (const current::net::HTTPRequestBodyLengthNotProvided&) {
- thrown = true;
- }
- }, std::move(reserved_port));
+ std::thread t(
+ [&thrown](Socket s) {
+ try {
+ HTTPServerConnection c(s.Accept());
+ ASSERT_TRUE(false);
+ } catch (const current::net::HTTPRequestBodyLengthNotProvided&) {
+ thrown = true;
+ }
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
connection.BlockingWrite("POST / HTTP/1.1\r\n", true);
connection.BlockingWrite("Host: localhost\r\n", true);
@@ -438,14 +462,16 @@ TEST(PosixHTTPServerTest, SmokePOSTBodyTooLong) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
std::atomic_bool thrown(false);
- std::thread t([&thrown](Socket s) {
- try {
- HTTPServerConnection c(s.Accept());
- ASSERT_TRUE(false);
- } catch (const current::net::HTTPPayloadTooLarge&) {
- thrown = true;
- }
- }, std::move(reserved_port));
+ std::thread t(
+ [&thrown](Socket s) {
+ try {
+ HTTPServerConnection c(s.Accept());
+ ASSERT_TRUE(false);
+ } catch (const current::net::HTTPPayloadTooLarge&) {
+ thrown = true;
+ }
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
try {
connection.BlockingWrite("POST / HTTP/1.1\r\n", true);
@@ -478,12 +504,14 @@ TEST(PosixHTTPServerTest, SmokePOSTBodyTooLong) {
TEST(PosixHTTPServerTest, LargeBody) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
- std::thread t([](Socket s) {
- HTTPServerConnection c(s.Accept());
- EXPECT_EQ("POST", c.HTTPRequest().Method());
- EXPECT_EQ("/", c.HTTPRequest().RawPath());
- c.SendHTTPResponse(std::string("Data: ") + c.HTTPRequest().Body());
- }, std::move(reserved_port));
+ std::thread t(
+ [](Socket s) {
+ HTTPServerConnection c(s.Accept());
+ EXPECT_EQ("POST", c.HTTPRequest().Method());
+ EXPECT_EQ("/", c.HTTPRequest().RawPath());
+ c.SendHTTPResponse(std::string("Data: ") + c.HTTPRequest().Body());
+ },
+ std::move(reserved_port));
std::string body(1000000, '.');
for (size_t i = 0; i < body.length(); ++i) {
body[i] = 'A' + (i % 26);
@@ -509,12 +537,14 @@ TEST(PosixHTTPServerTest, LargeBody) {
TEST(PosixHTTPServerTest, ChunkedLargeBodyManyChunks) {
auto reserved_port = current::net::ReserveLocalPort();
const int port = reserved_port;
- std::thread t([](Socket s) {
- HTTPServerConnection c(s.Accept());
- EXPECT_EQ("POST", c.HTTPRequest().Method());
- EXPECT_EQ("/", c.HTTPRequest().RawPath());
- c.SendHTTPResponse(c.HTTPRequest().Body());
- }, std::move(reserved_port));
+ std::thread t(
+ [](Socket s) {
+ HTTPServerConnection c(s.Accept());
+ EXPECT_EQ("POST", c.HTTPRequest().Method());
+ EXPECT_EQ("/", c.HTTPRequest().RawPath());
+ c.SendHTTPResponse(c.HTTPRequest().Body());
+ },
+ std::move(reserved_port));
Connection connection(ClientSocket("localhost", port));
connection.BlockingWrite("POST / HTTP/1.1\r\n", true);
connection.BlockingWrite("Host: localhost\r\n", true);
@@ -532,13 +562,12 @@ TEST(PosixHTTPServerTest, ChunkedLargeBodyManyChunks) {
connection.BlockingWrite("\r\n", true);
}
connection.BlockingWrite("0\r\n", false);
- ExpectToReceive(current::strings::Printf(
- "HTTP/1.1 200 OK\r\n"
- "Content-Type: text/plain\r\n"
- "Connection: close\r\n"
- "Content-Length: %d\r\n"
- "\r\n",
- static_cast(body.length())) +
+ ExpectToReceive(current::strings::Printf("HTTP/1.1 200 OK\r\n"
+ "Content-Type: text/plain\r\n"
+ "Connection: close\r\n"
+ "Content-Length: %d\r\n"
+ "\r\n",
+ static_cast(body.length())) +
body,
connection);
t.join();
@@ -572,8 +601,8 @@ TEST(PosixHTTPServerTest, ChunkedSmoke)
for (uint64_t i = 0; i < chunks; ++i) {
const uint64_t start = offset + length * i / chunks;
const uint64_t end = offset + length * (i + 1) / chunks;
- chunked_body +=
- current::strings::Printf("%llX\r\n", static_cast