feat: implement MoloApp plans 01-15 with integration
Full C++23 framework tree: runtime, observability, security, data, app, realtime, supervisor, clients, CLI, example plus enterprise tenancy, audit, operability, governance, supplychain. Postgres via docker compose for tests.
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
#pragma once
|
||||
|
||||
// Minimal dependency-free test framework for the clients part.
|
||||
|
||||
#include <functional>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace clients_test {
|
||||
|
||||
struct Failure : std::runtime_error {
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
|
||||
struct Case {
|
||||
std::string suite;
|
||||
std::string name;
|
||||
std::function<void()> fn;
|
||||
};
|
||||
|
||||
inline std::vector<Case>& registry() {
|
||||
static std::vector<Case> cases;
|
||||
return cases;
|
||||
}
|
||||
|
||||
struct Registrar {
|
||||
Registrar(const std::string& suite, const std::string& name,
|
||||
std::function<void()> fn) {
|
||||
registry().push_back(Case{suite, name, std::move(fn)});
|
||||
}
|
||||
};
|
||||
|
||||
int run_all();
|
||||
|
||||
template <typename T>
|
||||
std::string show(const T& value) {
|
||||
std::ostringstream out;
|
||||
out << value;
|
||||
return out.str();
|
||||
}
|
||||
|
||||
inline std::string show(const std::string& value) { return "'" + value + "'"; }
|
||||
inline std::string show(const char* value) {
|
||||
return value ? "'" + std::string(value) + "'" : "<null>";
|
||||
}
|
||||
inline std::string show(bool value) { return value ? "true" : "false"; }
|
||||
|
||||
} // namespace clients_test
|
||||
|
||||
#define TEST(suite, name) \
|
||||
static void clients_test_fn_##suite##_##name(); \
|
||||
static ::clients_test::Registrar clients_test_reg_##suite##_##name( \
|
||||
#suite, #name, clients_test_fn_##suite##_##name); \
|
||||
static void clients_test_fn_##suite##_##name()
|
||||
|
||||
#define ASSERT_TRUE(cond) \
|
||||
do { \
|
||||
if (!(cond)) { \
|
||||
std::ostringstream clients_test_msg; \
|
||||
clients_test_msg << __FILE__ << ":" << __LINE__ \
|
||||
<< ": ASSERT_TRUE failed: " #cond; \
|
||||
throw ::clients_test::Failure(clients_test_msg.str()); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define ASSERT_FALSE(cond) ASSERT_TRUE(!(cond))
|
||||
|
||||
#define ASSERT_EQ(a, b) \
|
||||
do { \
|
||||
auto clients_test_a = (a); \
|
||||
auto clients_test_b = (b); \
|
||||
if (!(clients_test_a == clients_test_b)) { \
|
||||
std::ostringstream clients_test_msg; \
|
||||
clients_test_msg << __FILE__ << ":" << __LINE__ << ": ASSERT_EQ (" \
|
||||
<< #a << " == " << #b << ") failed: got " \
|
||||
<< ::clients_test::show(clients_test_a) \
|
||||
<< ", want " << ::clients_test::show(clients_test_b); \
|
||||
throw ::clients_test::Failure(clients_test_msg.str()); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define ASSERT_THROW(stmt, exc_type) \
|
||||
do { \
|
||||
bool clients_test_caught = false; \
|
||||
try { \
|
||||
stmt; \
|
||||
} catch (const exc_type&) { \
|
||||
clients_test_caught = true; \
|
||||
} \
|
||||
if (!clients_test_caught) { \
|
||||
std::ostringstream clients_test_msg; \
|
||||
clients_test_msg << __FILE__ << ":" << __LINE__ \
|
||||
<< ": ASSERT_THROW failed: " #stmt \
|
||||
<< " did not throw " #exc_type; \
|
||||
throw ::clients_test::Failure(clients_test_msg.str()); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define FAIL(msg) \
|
||||
do { \
|
||||
std::ostringstream clients_test_msg; \
|
||||
clients_test_msg << __FILE__ << ":" << __LINE__ << ": " << msg; \
|
||||
throw ::clients_test::Failure(clients_test_msg.str()); \
|
||||
} while (0)
|
||||
@@ -0,0 +1,44 @@
|
||||
#include "framework.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
|
||||
namespace clients_test {
|
||||
|
||||
int run_all() {
|
||||
// Loopback tests must never be proxied; proxy tests set their own env.
|
||||
unsetenv("HTTP_PROXY");
|
||||
unsetenv("HTTPS_PROXY");
|
||||
unsetenv("NO_PROXY");
|
||||
unsetenv("http_proxy");
|
||||
unsetenv("https_proxy");
|
||||
unsetenv("no_proxy");
|
||||
int passed = 0;
|
||||
int failed = 0;
|
||||
for (const auto& test : registry()) {
|
||||
try {
|
||||
test.fn();
|
||||
++passed;
|
||||
std::cout << "ok " << test.suite << "." << test.name << "\n";
|
||||
} catch (const Failure& err) {
|
||||
++failed;
|
||||
std::cout << "FAIL " << test.suite << "." << test.name << ": " << err.what()
|
||||
<< "\n";
|
||||
} catch (const std::exception& err) {
|
||||
++failed;
|
||||
std::cout << "FAIL " << test.suite << "." << test.name
|
||||
<< ": uncaught std::exception: " << err.what() << "\n";
|
||||
} catch (...) {
|
||||
++failed;
|
||||
std::cout << "FAIL " << test.suite << "." << test.name
|
||||
<< ": uncaught unknown exception\n";
|
||||
}
|
||||
}
|
||||
std::cout << "passed " << passed << " failed " << failed << " total "
|
||||
<< (passed + failed) << "\n";
|
||||
return failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
} // namespace clients_test
|
||||
|
||||
int main() { return clients_test::run_all(); }
|
||||
@@ -0,0 +1,141 @@
|
||||
#include "framework.h"
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
#include "clients/body/form.h"
|
||||
#include "clients/body/json.h"
|
||||
#include "clients/body/stream.h"
|
||||
#include "clients/body/xml.h"
|
||||
|
||||
using namespace molo::clients::body;
|
||||
|
||||
TEST(bodies, json_roundtrip) {
|
||||
std::string text =
|
||||
R"({"name":"ada","age":36,"admin":true,"tags":["a","b"],"addr":{"city":"x"},"nil":null})";
|
||||
Json parsed = Json::parse(text);
|
||||
ASSERT_TRUE(parsed.is_object());
|
||||
ASSERT_EQ(parsed.find("name")->as_string(), "ada");
|
||||
ASSERT_EQ(parsed.find("age")->as_int(), 36);
|
||||
ASSERT_TRUE(parsed.find("admin")->as_bool());
|
||||
ASSERT_EQ(parsed.find("tags")->as_array().size(), 2u);
|
||||
ASSERT_TRUE(parsed.find("nil")->is_null());
|
||||
Json again = Json::parse(parsed.dump());
|
||||
ASSERT_TRUE(again.equals(parsed));
|
||||
// Deterministic key order: sorted.
|
||||
ASSERT_TRUE(parsed.dump().rfind("{\"addr\":", 0) == 0);
|
||||
}
|
||||
|
||||
TEST(bodies, json_escapes_and_numbers) {
|
||||
Json parsed = Json::parse(R"({"s":"a\"b\\c\nd\u00e9","n":-12.5e2})");
|
||||
ASSERT_EQ(parsed.find("s")->as_string(), "a\"b\\c\nd\xc3\xa9");
|
||||
ASSERT_EQ(parsed.find("n")->as_number(), -1250.0);
|
||||
ASSERT_THROW(Json::parse("{bad}"), JsonError);
|
||||
ASSERT_THROW(Json::parse("[1,]"), JsonError);
|
||||
ASSERT_THROW(Json::parse("\"unterminated"), JsonError);
|
||||
}
|
||||
|
||||
TEST(bodies, json_depth_cap) {
|
||||
std::string deep(40, '[');
|
||||
deep += std::string(40, ']');
|
||||
ASSERT_THROW(Json::parse(deep), JsonError);
|
||||
// Exactly at the cap parses.
|
||||
std::string ok(32, '[');
|
||||
ok += std::string(32, ']');
|
||||
ASSERT_TRUE(Json::parse(ok).is_array());
|
||||
}
|
||||
|
||||
TEST(bodies, yaml_dump) {
|
||||
Json doc = Json::object();
|
||||
doc.set("openapi", Json("3.1.0"));
|
||||
Json info = Json::object();
|
||||
info.set("title", Json("demo"));
|
||||
doc.set("info", info);
|
||||
Json list = Json::array();
|
||||
list.push(Json("a"));
|
||||
list.push(Json(1));
|
||||
doc.set("list", list);
|
||||
std::string yaml = yaml_dump(doc);
|
||||
ASSERT_TRUE(yaml.find("openapi: 3.1.0") != std::string::npos);
|
||||
ASSERT_TRUE(yaml.find("title: demo") != std::string::npos);
|
||||
ASSERT_TRUE(yaml.find("- a") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(bodies, form_urlencoded) {
|
||||
UrlEncodedForm form;
|
||||
form.add("name", "a b");
|
||||
form.add("q", "x+y&z=");
|
||||
std::string enc = form.encode();
|
||||
ASSERT_TRUE(enc.find("name=a%20b") != std::string::npos);
|
||||
UrlEncodedForm back = UrlEncodedForm::decode(enc);
|
||||
ASSERT_EQ(back.fields().size(), 2u);
|
||||
ASSERT_EQ(back.fields()[1].second, "x+y&z=");
|
||||
}
|
||||
|
||||
TEST(bodies, multipart) {
|
||||
MultipartBody body("testboundary");
|
||||
body.add_text("field", "value");
|
||||
body.add_file("file", "a.txt", "text/plain", "hello");
|
||||
std::string enc = body.encode();
|
||||
ASSERT_EQ(body.content_type(),
|
||||
"multipart/form-data; boundary=testboundary");
|
||||
ASSERT_TRUE(enc.find("--testboundary\r\n") != std::string::npos);
|
||||
ASSERT_TRUE(enc.find("filename=\"a.txt\"") != std::string::npos);
|
||||
ASSERT_TRUE(enc.find("\r\nhello\r\n") != std::string::npos);
|
||||
ASSERT_TRUE(enc.find("--testboundary--\r\n") != std::string::npos);
|
||||
ASSERT_TRUE(body.encoded_size() > 0);
|
||||
}
|
||||
|
||||
TEST(bodies, xml_builder_and_parse) {
|
||||
XmlBuilder builder("user");
|
||||
builder.attr("id", "7").child("name", "a<b").child("empty", "");
|
||||
std::string text = builder.str();
|
||||
ASSERT_TRUE(text.find("<user id=\"7\">") != std::string::npos);
|
||||
ASSERT_TRUE(text.find("<") != std::string::npos);
|
||||
auto flat = xml_parse_flat(text);
|
||||
ASSERT_EQ(flat["name"], "a<b");
|
||||
ASSERT_THROW(xml_parse_flat("<a><b><c/></b></a>"), XmlError);
|
||||
ASSERT_THROW(xml_parse_flat("nope"), XmlError);
|
||||
}
|
||||
|
||||
TEST(bodies, stream_readers) {
|
||||
StringReader reader("0123456789");
|
||||
ASSERT_EQ(reader.read_some(4), "0123");
|
||||
ASSERT_EQ(reader.read_some(100), "456789");
|
||||
ASSERT_TRUE(reader.eof());
|
||||
ASSERT_TRUE(reader.known_size().has_value());
|
||||
|
||||
bool eof = false;
|
||||
CallbackReader callback(
|
||||
[&](std::size_t max_bytes, bool& done) {
|
||||
(void)max_bytes;
|
||||
done = true;
|
||||
return std::string("cb");
|
||||
},
|
||||
2u);
|
||||
ASSERT_EQ(callback.read_some(64), "cb");
|
||||
ASSERT_TRUE(callback.eof());
|
||||
ASSERT_TRUE(callback.known_size().has_value());
|
||||
(void)eof;
|
||||
|
||||
const char* path = "build/clients_test_tmp.bin";
|
||||
{
|
||||
std::FILE* file = std::fopen(path, "wb");
|
||||
ASSERT_TRUE(file != nullptr);
|
||||
std::fwrite("filedata", 1, 8, file);
|
||||
std::fclose(file);
|
||||
}
|
||||
FileReader file_reader(path);
|
||||
ASSERT_EQ(file_reader.read_some(4), "file");
|
||||
ASSERT_EQ(file_reader.read_some(4), "data");
|
||||
ASSERT_TRUE(file_reader.eof());
|
||||
std::remove(path);
|
||||
ASSERT_THROW(FileReader("build/does-not-exist-molo.bin"), StreamError);
|
||||
}
|
||||
|
||||
TEST(bodies, capped_collector) {
|
||||
CappedCollector collector(4);
|
||||
ASSERT_TRUE(collector.push("ab"));
|
||||
ASSERT_TRUE(collector.push("cd"));
|
||||
ASSERT_EQ(collector.data(), "abcd");
|
||||
ASSERT_THROW(collector.push("e"), StreamError);
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
#include "framework.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "clients/auth.h"
|
||||
#include "clients/client.h"
|
||||
#include "clients/transports/mock_transport.h"
|
||||
|
||||
using namespace molo::clients;
|
||||
using molo::clients::transports::MockTransport;
|
||||
|
||||
namespace {
|
||||
|
||||
struct RecordingReporter : Reporter {
|
||||
std::vector<RequestSpan> spans;
|
||||
void on_request(const RequestSpan& span) override { spans.push_back(span); }
|
||||
};
|
||||
|
||||
ClientResponse text_response(int status, const std::string& body) {
|
||||
HeaderMap headers;
|
||||
headers.set("Content-Type", "text/plain");
|
||||
return ClientResponse(status, std::move(headers), body);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(client, verbs_over_mock) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
mock->expect_status(Method::kGet, "/v1/users", 200, "[]",
|
||||
"application/json");
|
||||
mock->expect_status(Method::kPost, "/v1/users", 201, "{}",
|
||||
"application/json");
|
||||
Client client(std::move(mock));
|
||||
ClientResponse list = client.get_blocking("http://api.test/v1/users");
|
||||
ASSERT_EQ(list.status(), 200);
|
||||
ASSERT_EQ(list.body(), "[]");
|
||||
ClientResponse created =
|
||||
client.post_blocking("http://api.test/v1/users", "{}", "application/json");
|
||||
ASSERT_EQ(created.status(), 201);
|
||||
raw->verify();
|
||||
ASSERT_EQ(raw->send_count(), 2u);
|
||||
}
|
||||
|
||||
TEST(client, template_and_predicates) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
transports::MockExpectation exp;
|
||||
exp.method = Method::kGet;
|
||||
exp.path = "/v1/users/{id}";
|
||||
exp.required_headers["X-Tenant"] = "acme";
|
||||
exp.response = text_response(200, "user");
|
||||
raw->expect(std::move(exp));
|
||||
Client client(std::move(mock));
|
||||
ClientRequest req = ClientRequest::get("http://api.test/v1/users/42");
|
||||
req.header("X-Tenant", "acme");
|
||||
ASSERT_EQ(client.send_blocking(std::move(req)).status(), 200);
|
||||
raw->verify();
|
||||
}
|
||||
|
||||
TEST(client, request_helpers_and_json) {
|
||||
ClientRequest req = ClientRequest::post("http://h/x");
|
||||
body::Json doc = body::Json::object();
|
||||
doc.set("a", body::Json(1));
|
||||
req.json(doc);
|
||||
ASSERT_EQ(req.headers().get_or("Content-Type", ""), "application/json");
|
||||
ASSERT_TRUE(req.body_bytes().find("\"a\":1") != std::string::npos);
|
||||
ClientRequest form = ClientRequest::post("http://h/f");
|
||||
body::UrlEncodedForm fields;
|
||||
fields.add("k", "v");
|
||||
form.form(fields);
|
||||
ASSERT_EQ(form.body_bytes(), "k=v");
|
||||
}
|
||||
|
||||
TEST(client, connect_error_retries_then_succeeds) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
raw->expect_error(Method::kGet, "/flaky",
|
||||
std::make_exception_ptr(TimeoutError(TimeoutPhase::kConnect)));
|
||||
raw->expect_status(Method::kGet, "/flaky", 200, "ok");
|
||||
ClientConfig config;
|
||||
std::vector<std::chrono::milliseconds> sleeps;
|
||||
config.sleeper = [&](std::chrono::milliseconds ms) { sleeps.push_back(ms); };
|
||||
Client client(std::move(mock), config);
|
||||
ClientResponse resp = client.get_blocking("http://h/flaky");
|
||||
ASSERT_EQ(resp.status(), 200);
|
||||
ASSERT_EQ(resp.attempts(), 2);
|
||||
ASSERT_EQ(sleeps.size(), 1u);
|
||||
ASSERT_EQ(client.stats().retries, 1u);
|
||||
raw->verify();
|
||||
}
|
||||
|
||||
TEST(client, retryable_status_matrix) {
|
||||
for (int status : {429, 502, 503, 504}) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
raw->expect_status(Method::kGet, "/r", status, "bad");
|
||||
raw->expect_status(Method::kGet, "/r", 200, "good");
|
||||
ClientConfig config;
|
||||
config.sleeper = [](std::chrono::milliseconds) {};
|
||||
Client client(std::move(mock), config);
|
||||
ClientResponse resp = client.get_blocking("http://h/r");
|
||||
ASSERT_EQ(resp.status(), 200);
|
||||
ASSERT_EQ(resp.attempts(), 2);
|
||||
raw->verify();
|
||||
}
|
||||
// Non-retryable status passes through untouched.
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
mock->expect_status(Method::kGet, "/r", 500, "bad");
|
||||
Client client(std::move(mock));
|
||||
ASSERT_EQ(client.get_blocking("http://h/r").attempts(), 1);
|
||||
}
|
||||
|
||||
TEST(client, post_not_retried_without_idempotency) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
raw->expect_status(Method::kPost, "/orders", 503, "busy");
|
||||
ClientConfig config;
|
||||
config.sleeper = [](std::chrono::milliseconds) {};
|
||||
Client client(std::move(mock), config);
|
||||
ClientResponse resp = client.post_blocking("http://h/orders", "{}");
|
||||
ASSERT_EQ(resp.status(), 503);
|
||||
ASSERT_EQ(resp.attempts(), 1);
|
||||
ASSERT_EQ(raw->send_count(), 1u);
|
||||
raw->verify();
|
||||
}
|
||||
|
||||
TEST(client, post_retried_with_idempotency_key) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
raw->expect_status(Method::kPost, "/orders", 503, "busy");
|
||||
raw->expect_status(Method::kPost, "/orders", 200, "done");
|
||||
ClientConfig config;
|
||||
config.sleeper = [](std::chrono::milliseconds) {};
|
||||
Client client(std::move(mock), config);
|
||||
ClientRequest req = ClientRequest::post("http://h/orders");
|
||||
req.json_text("{}");
|
||||
req.idempotency_key("key-123");
|
||||
ClientResponse resp = client.send_blocking(std::move(req));
|
||||
ASSERT_EQ(resp.status(), 200);
|
||||
ASSERT_EQ(resp.attempts(), 2);
|
||||
raw->verify();
|
||||
// The key was actually sent.
|
||||
auto seen = raw->seen();
|
||||
ASSERT_EQ(seen.size(), 2u);
|
||||
ASSERT_EQ(seen[0].headers.get_or("Idempotency-Key", ""), "key-123");
|
||||
}
|
||||
|
||||
TEST(client, retry_after_honored) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
HeaderMap headers;
|
||||
headers.set("Content-Type", "text/plain");
|
||||
headers.set("Retry-After", "2");
|
||||
transports::MockExpectation exp;
|
||||
exp.method = Method::kGet;
|
||||
exp.path = "/limited";
|
||||
exp.response = ClientResponse(429, headers, "slow down");
|
||||
raw->expect(std::move(exp));
|
||||
raw->expect_status(Method::kGet, "/limited", 200, "ok");
|
||||
ClientConfig config;
|
||||
std::vector<std::chrono::milliseconds> sleeps;
|
||||
config.sleeper = [&](std::chrono::milliseconds ms) { sleeps.push_back(ms); };
|
||||
Client client(std::move(mock), config);
|
||||
ASSERT_EQ(client.get_blocking("http://h/limited").status(), 200);
|
||||
ASSERT_EQ(sleeps.size(), 1u);
|
||||
ASSERT_EQ(sleeps[0].count(), 2000);
|
||||
raw->verify();
|
||||
}
|
||||
|
||||
TEST(client, retry_after_capped) {
|
||||
ASSERT_EQ(RetryPolicy::parse_retry_after("120")->count(), 5000);
|
||||
ASSERT_TRUE(!RetryPolicy::parse_retry_after("garbage").has_value());
|
||||
ASSERT_TRUE(!RetryPolicy::parse_retry_after("").has_value());
|
||||
// HTTP-date in the past yields zero delay.
|
||||
auto past =
|
||||
RetryPolicy::parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT");
|
||||
ASSERT_TRUE(past.has_value());
|
||||
ASSERT_EQ(past->count(), 0);
|
||||
}
|
||||
|
||||
TEST(client, backoff_bounds) {
|
||||
RetryPolicy::set_test_seed(42);
|
||||
RetryPolicy policy;
|
||||
for (int i = 0; i < 50; ++i) {
|
||||
auto d1 = policy.backoff_for(1);
|
||||
ASSERT_TRUE(d1.count() >= 0 && d1.count() <= 200);
|
||||
auto d3 = policy.backoff_for(3);
|
||||
ASSERT_TRUE(d3.count() >= 0 && d3.count() <= 800);
|
||||
auto d30 = policy.backoff_for(30);
|
||||
ASSERT_TRUE(d30.count() >= 0 && d30.count() <= 5000);
|
||||
}
|
||||
RetryPolicy::set_test_seed(-1);
|
||||
}
|
||||
|
||||
TEST(client, redirect_follow_relative) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
HeaderMap headers;
|
||||
headers.set("Location", "/v1/target");
|
||||
transports::MockExpectation exp;
|
||||
exp.method = Method::kGet;
|
||||
exp.path = "/v1/start";
|
||||
exp.response = ClientResponse(302, headers, "");
|
||||
raw->expect(std::move(exp));
|
||||
raw->expect_status(Method::kGet, "/v1/target", 200, "there");
|
||||
Client client(std::move(mock));
|
||||
ClientResponse resp = client.get_blocking("http://h/v1/start");
|
||||
ASSERT_EQ(resp.status(), 200);
|
||||
ASSERT_EQ(resp.body(), "there");
|
||||
ASSERT_EQ(client.stats().redirect_hops, 1u);
|
||||
raw->verify();
|
||||
}
|
||||
|
||||
TEST(client, redirect_strips_auth_cross_host) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
HeaderMap headers;
|
||||
headers.set("Location", "http://other.test/v1/target");
|
||||
transports::MockExpectation exp;
|
||||
exp.method = Method::kGet;
|
||||
exp.path = "/v1/start";
|
||||
exp.response = ClientResponse(302, headers, "");
|
||||
raw->expect(std::move(exp));
|
||||
raw->expect_status(Method::kGet, "/v1/target", 200, "there");
|
||||
ClientConfig config;
|
||||
config.auth = std::make_shared<BearerAuth>("secret");
|
||||
Client client(std::move(mock), config);
|
||||
ASSERT_EQ(client.get_blocking("http://h/v1/start").status(), 200);
|
||||
auto seen = raw->seen();
|
||||
ASSERT_EQ(seen.size(), 2u);
|
||||
ASSERT_EQ(seen[0].headers.get_or("Authorization", ""), "Bearer secret");
|
||||
ASSERT_FALSE(seen[1].headers.has("Authorization"));
|
||||
raw->verify();
|
||||
}
|
||||
|
||||
TEST(client, redirect_loop_bounded) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
HeaderMap headers;
|
||||
headers.set("Location", "/loop");
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
transports::MockExpectation exp;
|
||||
exp.method = Method::kGet;
|
||||
exp.path = "/loop";
|
||||
exp.response = ClientResponse(302, headers, "");
|
||||
mock->expect(std::move(exp));
|
||||
}
|
||||
Client client(std::move(mock));
|
||||
ASSERT_THROW(client.get_blocking("http://h/loop"), RedirectError);
|
||||
}
|
||||
|
||||
TEST(client, post_redirect_not_followed) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
HeaderMap headers;
|
||||
headers.set("Location", "/elsewhere");
|
||||
transports::MockExpectation exp;
|
||||
exp.method = Method::kPost;
|
||||
exp.path = "/submit";
|
||||
exp.response = ClientResponse(302, headers, "");
|
||||
raw->expect(std::move(exp));
|
||||
Client client(std::move(mock));
|
||||
ClientResponse resp = client.post_blocking("http://h/submit", "x");
|
||||
ASSERT_EQ(resp.status(), 302);
|
||||
ASSERT_EQ(raw->send_count(), 1u);
|
||||
raw->verify();
|
||||
}
|
||||
|
||||
TEST(client, cookie_jar_roundtrip) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
HeaderMap login_headers;
|
||||
login_headers.set("Content-Type", "text/plain");
|
||||
login_headers.add("Set-Cookie", "session=abc; Path=/; HttpOnly");
|
||||
transports::MockExpectation login;
|
||||
login.method = Method::kPost;
|
||||
login.path = "/login";
|
||||
login.response = ClientResponse(200, login_headers, "ok");
|
||||
raw->expect(std::move(login));
|
||||
transports::MockExpectation me;
|
||||
me.method = Method::kGet;
|
||||
me.path = "/me";
|
||||
me.required_headers["Cookie"] = "session=abc";
|
||||
me.response = text_response(200, "me");
|
||||
raw->expect(std::move(me));
|
||||
Client client(std::move(mock));
|
||||
ASSERT_EQ(client.post_blocking("http://h/login", "").status(), 200);
|
||||
ASSERT_EQ(client.get_blocking("http://h/me").body(), "me");
|
||||
ASSERT_EQ(client.jar().size(), 1u);
|
||||
raw->verify();
|
||||
}
|
||||
|
||||
TEST(client, secure_cookie_not_sent_over_http) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
HeaderMap login_headers;
|
||||
login_headers.add("Set-Cookie", "s=1; Secure; Path=/");
|
||||
transports::MockExpectation login;
|
||||
login.method = Method::kGet;
|
||||
login.path = "/login";
|
||||
login.response = ClientResponse(200, login_headers, "ok");
|
||||
raw->expect(std::move(login));
|
||||
transports::MockExpectation next;
|
||||
next.method = Method::kGet;
|
||||
next.path = "/next";
|
||||
next.predicate = [](const ClientRequest& req) {
|
||||
return !req.headers().has("Cookie");
|
||||
};
|
||||
next.response = text_response(200, "ok");
|
||||
raw->expect(std::move(next));
|
||||
Client client(std::move(mock));
|
||||
client.get_blocking("http://h/login");
|
||||
client.get_blocking("http://h/next");
|
||||
raw->verify();
|
||||
}
|
||||
|
||||
TEST(client, auth_basic_and_apikey) {
|
||||
BasicAuth basic("user", "pass");
|
||||
ClientRequest req = ClientRequest::get("http://h/x");
|
||||
basic.apply(req);
|
||||
ASSERT_EQ(req.headers().get_or("Authorization", ""),
|
||||
"Basic dXNlcjpwYXNz");
|
||||
ApiKeyAuth key("k", "X-Api-Key");
|
||||
ClientRequest req2 = ClientRequest::get("http://h/x");
|
||||
key.apply(req2);
|
||||
ASSERT_EQ(req2.headers().get_or("X-Api-Key", ""), "k");
|
||||
ApiKeyAuth query_key("k", "X-Api-Key", "api_key");
|
||||
ClientRequest req3 = ClientRequest::get("http://h/x");
|
||||
query_key.apply(req3);
|
||||
ASSERT_TRUE(req3.url().target().find("api_key=k") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(client, base_url_and_reporter) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
raw->expect_status(Method::kGet, "/v1/ping", 200, "pong");
|
||||
auto reporter = std::make_shared<RecordingReporter>();
|
||||
ClientConfig config;
|
||||
config.base_url = "http://api.test";
|
||||
config.reporter = reporter;
|
||||
Client client(std::move(mock), config);
|
||||
ClientResponse resp = client.get_blocking("/v1/ping");
|
||||
ASSERT_EQ(resp.body(), "pong");
|
||||
ASSERT_EQ(reporter->spans.size(), 1u);
|
||||
ASSERT_EQ(reporter->spans[0].status, 200);
|
||||
ASSERT_EQ(reporter->spans[0].method, "GET");
|
||||
ASSERT_EQ(client.stats().requests, 1u);
|
||||
ASSERT_EQ(client.stats().responses_2xx, 1u);
|
||||
raw->verify();
|
||||
}
|
||||
|
||||
TEST(client, unmatched_and_unconsumed) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
raw->expect_status(Method::kGet, "/known", 200, "x");
|
||||
Client client(std::move(mock));
|
||||
ASSERT_THROW(client.get_blocking("http://h/unknown"),
|
||||
transports::MockError);
|
||||
ASSERT_THROW(raw->verify(), transports::MockError);
|
||||
}
|
||||
|
||||
TEST(client, stream_upload_mock) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
raw->expect_status(Method::kPost, "/upload", 200, "stored");
|
||||
Client client(std::move(mock));
|
||||
auto reader = std::make_shared<body::StringReader>("chunked-data");
|
||||
ClientRequest req = ClientRequest::post("http://h/upload");
|
||||
req.stream(reader, std::nullopt, "application/octet-stream");
|
||||
ASSERT_TRUE(req.is_stream_body());
|
||||
ASSERT_EQ(client.send_blocking(std::move(req)).status(), 200);
|
||||
raw->verify();
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
#include "framework.h"
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <poll.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "clients/client.h"
|
||||
#include "clients/transports/http_transport.h"
|
||||
#include "clients/transports/tls.h"
|
||||
|
||||
using namespace molo::clients;
|
||||
using molo::clients::transports::BodyTooLargeError;
|
||||
using molo::clients::transports::H2StubError;
|
||||
using molo::clients::transports::HttpTransport;
|
||||
using molo::clients::transports::TlsStubError;
|
||||
|
||||
namespace {
|
||||
|
||||
std::string to_lower(std::string s) {
|
||||
for (auto& c : s) c = (char)tolower((unsigned char)c);
|
||||
return s;
|
||||
}
|
||||
|
||||
bool recv_until(int fd, std::string& buf, const std::string& marker) {
|
||||
char chunk[4096];
|
||||
while (buf.find(marker) == std::string::npos) {
|
||||
struct pollfd pfd {fd, POLLIN, 0};
|
||||
if (::poll(&pfd, 1, 5000) <= 0) return false;
|
||||
ssize_t r = ::recv(fd, chunk, sizeof(chunk), 0);
|
||||
if (r <= 0) return false;
|
||||
buf.append(chunk, (std::size_t)r);
|
||||
if (buf.size() > 1024 * 1024) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool recv_line(int fd, std::string& buf, std::string& line) {
|
||||
if (!recv_until(fd, buf, "\r\n")) return false;
|
||||
auto at = buf.find("\r\n");
|
||||
line = buf.substr(0, at);
|
||||
buf.erase(0, at + 2);
|
||||
return true;
|
||||
}
|
||||
|
||||
void send_all(int fd, const std::string& data) {
|
||||
std::size_t sent = 0;
|
||||
while (sent < data.size()) {
|
||||
ssize_t n = ::send(fd, data.data() + sent, data.size() - sent, MSG_NOSIGNAL);
|
||||
if (n <= 0) return;
|
||||
sent += (std::size_t)n;
|
||||
}
|
||||
}
|
||||
|
||||
// Minimal loopback HTTP/1.1 server for real-transport tests.
|
||||
class LoopServer {
|
||||
public:
|
||||
LoopServer() {
|
||||
listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
int one = 1;
|
||||
::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
|
||||
struct sockaddr_in addr {};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
addr.sin_port = 0;
|
||||
::bind(listen_fd_, (struct sockaddr*)&addr, sizeof(addr));
|
||||
::listen(listen_fd_, 16);
|
||||
socklen_t len = sizeof(addr);
|
||||
::getsockname(listen_fd_, (struct sockaddr*)&addr, &len);
|
||||
port_ = ntohs(addr.sin_port);
|
||||
thread_ = std::thread([this] { accept_loop(); });
|
||||
}
|
||||
|
||||
~LoopServer() {
|
||||
stop_ = true;
|
||||
::shutdown(listen_fd_, SHUT_RDWR);
|
||||
::close(listen_fd_);
|
||||
if (thread_.joinable()) thread_.join();
|
||||
}
|
||||
|
||||
int port() const { return port_; }
|
||||
int connections() const { return connections_; }
|
||||
int requests() const { return requests_; }
|
||||
|
||||
std::string base() const {
|
||||
return "http://127.0.0.1:" + std::to_string(port_);
|
||||
}
|
||||
|
||||
private:
|
||||
void accept_loop() {
|
||||
while (!stop_) {
|
||||
struct pollfd pfd {listen_fd_, POLLIN, 0};
|
||||
if (::poll(&pfd, 1, 100) <= 0) continue;
|
||||
int fd = ::accept(listen_fd_, nullptr, nullptr);
|
||||
if (fd < 0) continue;
|
||||
connections_++;
|
||||
handle_connection(fd);
|
||||
::close(fd);
|
||||
}
|
||||
}
|
||||
|
||||
void handle_connection(int fd) {
|
||||
std::string buf;
|
||||
for (int i = 0; i < 50 && !stop_; ++i) {
|
||||
if (!recv_until(fd, buf, "\r\n\r\n")) return;
|
||||
auto at = buf.find("\r\n\r\n");
|
||||
std::string head = buf.substr(0, at);
|
||||
buf.erase(0, at + 4);
|
||||
std::string request_line = head.substr(0, head.find("\r\n"));
|
||||
std::map<std::string, std::string> headers;
|
||||
std::size_t pos = head.find("\r\n");
|
||||
while (pos != std::string::npos) {
|
||||
std::size_t next = head.find("\r\n", pos + 2);
|
||||
std::string line = next == std::string::npos
|
||||
? head.substr(pos + 2)
|
||||
: head.substr(pos + 2, next - pos - 2);
|
||||
pos = next;
|
||||
auto colon = line.find(':');
|
||||
if (colon == std::string::npos) continue;
|
||||
headers[to_lower(line.substr(0, colon))] = line.substr(colon + 1);
|
||||
}
|
||||
// Trim header values.
|
||||
for (auto& kv : headers) {
|
||||
while (!kv.second.empty() && kv.second.front() == ' ')
|
||||
kv.second.erase(kv.second.begin());
|
||||
while (!kv.second.empty() && kv.second.back() == '\r')
|
||||
kv.second.pop_back();
|
||||
}
|
||||
std::string body;
|
||||
auto te = headers.find("transfer-encoding");
|
||||
auto cl = headers.find("content-length");
|
||||
if (te != headers.end() && te->second.find("chunked") != std::string::npos) {
|
||||
while (true) {
|
||||
std::string line;
|
||||
if (!recv_line(fd, buf, line)) return;
|
||||
long size = strtol(line.c_str(), nullptr, 16);
|
||||
if (size == 0) {
|
||||
std::string trailer;
|
||||
if (!recv_line(fd, buf, trailer)) return;
|
||||
break;
|
||||
}
|
||||
while ((long)buf.size() < size) {
|
||||
char chunk[4096];
|
||||
struct pollfd pfd {fd, POLLIN, 0};
|
||||
if (::poll(&pfd, 1, 5000) <= 0) return;
|
||||
ssize_t r = ::recv(fd, chunk, sizeof(chunk), 0);
|
||||
if (r <= 0) return;
|
||||
buf.append(chunk, (std::size_t)r);
|
||||
}
|
||||
body.append(buf.data(), (std::size_t)size);
|
||||
buf.erase(0, (std::size_t)size);
|
||||
std::string crlf;
|
||||
if (!recv_line(fd, buf, crlf)) return;
|
||||
}
|
||||
} else if (cl != headers.end()) {
|
||||
std::size_t need = (std::size_t)std::stoul(cl->second);
|
||||
while (buf.size() < need) {
|
||||
char chunk[4096];
|
||||
struct pollfd pfd {fd, POLLIN, 0};
|
||||
if (::poll(&pfd, 1, 5000) <= 0) return;
|
||||
ssize_t r = ::recv(fd, chunk, sizeof(chunk), 0);
|
||||
if (r <= 0) return;
|
||||
buf.append(chunk, (std::size_t)r);
|
||||
}
|
||||
body = buf.substr(0, need);
|
||||
buf.erase(0, need);
|
||||
}
|
||||
requests_++;
|
||||
std::string method = request_line.substr(0, request_line.find(' '));
|
||||
std::string target = "";
|
||||
{
|
||||
auto sp1 = request_line.find(' ');
|
||||
auto sp2 = request_line.find(' ', sp1 + 1);
|
||||
if (sp1 != std::string::npos && sp2 != std::string::npos)
|
||||
target = request_line.substr(sp1 + 1, sp2 - sp1 - 1);
|
||||
}
|
||||
auto q = target.find('?');
|
||||
std::string path = q == std::string::npos ? target : target.substr(0, q);
|
||||
// Absolute-form targets (proxied): reduce to origin-form.
|
||||
if (path.rfind("http://", 0) == 0) {
|
||||
auto slash = path.find('/', 7);
|
||||
path = slash == std::string::npos ? "/" : path.substr(slash);
|
||||
}
|
||||
std::string payload;
|
||||
std::string content_type = "text/plain";
|
||||
std::string extra_headers = "Connection: keep-alive\r\n";
|
||||
bool chunked_response = false;
|
||||
if (path == "/echo") {
|
||||
payload = method + " " + target + "\n" + body;
|
||||
} else if (path == "/keep") {
|
||||
payload = "keep-alive-ok";
|
||||
} else if (path == "/close") {
|
||||
payload = "closing";
|
||||
extra_headers = "Connection: close\r\n";
|
||||
} else if (path == "/chunked") {
|
||||
chunked_response = true;
|
||||
} else if (path == "/big") {
|
||||
payload = std::string(256 * 1024, 'x');
|
||||
} else if (path == "/slow") {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
payload = "slow-ok";
|
||||
} else {
|
||||
std::string not_found = "HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\n" +
|
||||
extra_headers + "\r\nnot found";
|
||||
send_all(fd, not_found);
|
||||
continue;
|
||||
}
|
||||
if (chunked_response) {
|
||||
send_all(fd, "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n" +
|
||||
extra_headers + "Content-Type: text/plain\r\n\r\n"
|
||||
"5\r\nhello\r\n6\r\n world\r\n1\r\n!\r\n0\r\n\r\n");
|
||||
} else {
|
||||
std::string response = "HTTP/1.1 200 OK\r\nContent-Length: " +
|
||||
std::to_string(payload.size()) + "\r\n" +
|
||||
extra_headers + "Content-Type: " + content_type +
|
||||
"\r\n\r\n" + payload;
|
||||
send_all(fd, response);
|
||||
}
|
||||
if (extra_headers.find("close") != std::string::npos) return;
|
||||
(void)content_type;
|
||||
}
|
||||
}
|
||||
|
||||
int listen_fd_ = -1;
|
||||
int port_ = 0;
|
||||
std::atomic<bool> stop_{false};
|
||||
std::atomic<int> connections_{0};
|
||||
std::atomic<int> requests_{0};
|
||||
std::thread thread_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(http, echo_roundtrip) {
|
||||
LoopServer server;
|
||||
Client client(std::make_unique<HttpTransport>());
|
||||
ClientResponse get = client.get_blocking(server.base() + "/echo?m=1");
|
||||
ASSERT_EQ(get.status(), 200);
|
||||
ASSERT_TRUE(get.body().find("GET /echo?m=1") != std::string::npos);
|
||||
ClientResponse post =
|
||||
client.post_blocking(server.base() + "/echo", "ping-body");
|
||||
ASSERT_EQ(post.status(), 200);
|
||||
ASSERT_TRUE(post.body().find("ping-body") != std::string::npos);
|
||||
ASSERT_EQ(server.requests(), 2);
|
||||
}
|
||||
|
||||
TEST(http, keepalive_reuse) {
|
||||
LoopServer server;
|
||||
Client client(std::make_unique<HttpTransport>());
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
ClientResponse resp = client.get_blocking(server.base() + "/keep");
|
||||
ASSERT_EQ(resp.body(), "keep-alive-ok");
|
||||
if (i > 0) ASSERT_TRUE(resp.from_pool_reuse());
|
||||
}
|
||||
ASSERT_EQ(server.connections(), 1);
|
||||
ASSERT_TRUE(client.pool().stats().reused >= 2);
|
||||
}
|
||||
|
||||
TEST(http, chunked_response) {
|
||||
LoopServer server;
|
||||
Client client(std::make_unique<HttpTransport>());
|
||||
ClientResponse resp = client.get_blocking(server.base() + "/chunked");
|
||||
ASSERT_EQ(resp.status(), 200);
|
||||
ASSERT_EQ(resp.body(), "hello world!");
|
||||
}
|
||||
|
||||
TEST(http, streamed_download) {
|
||||
LoopServer server;
|
||||
Client client(std::make_unique<HttpTransport>());
|
||||
std::size_t bytes = 0;
|
||||
int chunks = 0;
|
||||
ClientRequest req = ClientRequest::get(server.base() + "/big");
|
||||
client.send_stream_blocking(std::move(req), [&](const std::string& chunk) {
|
||||
bytes += chunk.size();
|
||||
chunks++;
|
||||
return true;
|
||||
});
|
||||
ASSERT_EQ(bytes, 256u * 1024u);
|
||||
ASSERT_TRUE(chunks > 1);
|
||||
// Cancellation stops the transfer without an error.
|
||||
ClientRequest req2 = ClientRequest::get(server.base() + "/big");
|
||||
int seen = 0;
|
||||
client.send_stream_blocking(std::move(req2), [&](const std::string&) {
|
||||
return ++seen < 2;
|
||||
});
|
||||
ASSERT_EQ(seen, 2);
|
||||
}
|
||||
|
||||
TEST(http, close_response_not_reused) {
|
||||
LoopServer server;
|
||||
Client client(std::make_unique<HttpTransport>());
|
||||
ASSERT_EQ(client.get_blocking(server.base() + "/close").status(), 200);
|
||||
ASSERT_EQ(client.get_blocking(server.base() + "/keep").status(), 200);
|
||||
ASSERT_EQ(server.connections(), 2);
|
||||
}
|
||||
|
||||
TEST(http, read_timeout_phase) {
|
||||
LoopServer server;
|
||||
auto transport = std::make_unique<HttpTransport>();
|
||||
Client client(std::move(transport));
|
||||
Timeouts timeouts;
|
||||
timeouts.read = std::chrono::milliseconds(100);
|
||||
timeouts.total = std::chrono::milliseconds(10000);
|
||||
ClientRequest req = ClientRequest::get(server.base() + "/slow");
|
||||
req.timeouts(timeouts);
|
||||
req.mark_idempotent(false);
|
||||
try {
|
||||
client.send_blocking(std::move(req));
|
||||
FAIL("expected TimeoutError");
|
||||
} catch (const TimeoutError& err) {
|
||||
ASSERT_TRUE(err.phase() == TimeoutPhase::kRead ||
|
||||
err.phase() == TimeoutPhase::kTotal);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(http, connect_refused_is_connect_phase) {
|
||||
int probe = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
struct sockaddr_in addr {};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
addr.sin_port = 0;
|
||||
::bind(probe, (struct sockaddr*)&addr, sizeof(addr));
|
||||
socklen_t len = sizeof(addr);
|
||||
::getsockname(probe, (struct sockaddr*)&addr, &len);
|
||||
int closed_port = ntohs(addr.sin_port);
|
||||
::close(probe);
|
||||
Client client(std::make_unique<HttpTransport>());
|
||||
try {
|
||||
client.get_blocking("http://127.0.0.1:" + std::to_string(closed_port) +
|
||||
"/");
|
||||
FAIL("expected TransportError");
|
||||
} catch (const TransportError& err) {
|
||||
ASSERT_TRUE(err.connect_phase());
|
||||
}
|
||||
}
|
||||
|
||||
TEST(http, https_needs_tls_stub) {
|
||||
LoopServer server;
|
||||
Client client(std::make_unique<HttpTransport>());
|
||||
ASSERT_THROW(client.get_blocking("https://127.0.0.1:" +
|
||||
std::to_string(server.port()) + "/"),
|
||||
TlsStubError);
|
||||
}
|
||||
|
||||
TEST(http, h2c_stub) {
|
||||
LoopServer server;
|
||||
Client client(std::make_unique<HttpTransport>());
|
||||
ClientRequest req = ClientRequest::get(server.base() + "/keep");
|
||||
req.h2(true);
|
||||
ASSERT_THROW(client.send_blocking(std::move(req)), H2StubError);
|
||||
}
|
||||
|
||||
TEST(http, buffered_body_cap) {
|
||||
Client client(std::make_unique<HttpTransport>());
|
||||
ClientRequest req = ClientRequest::post("http://127.0.0.1:9/echo");
|
||||
req.bytes(std::string(11 * 1024 * 1024, 'y'));
|
||||
ASSERT_THROW(client.send_blocking(std::move(req)), BodyTooLargeError);
|
||||
}
|
||||
|
||||
TEST(http, not_found_status) {
|
||||
LoopServer server;
|
||||
Client client(std::make_unique<HttpTransport>());
|
||||
ClientResponse resp = client.get_blocking(server.base() + "/missing");
|
||||
ASSERT_EQ(resp.status(), 404);
|
||||
ASSERT_EQ(resp.body(), "not found");
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
#include "framework.h"
|
||||
|
||||
#include "clients/openapi/builder.h"
|
||||
#include "clients/openapi/document.h"
|
||||
#include "clients/openapi/extensions.h"
|
||||
#include "clients/openapi/routes.h"
|
||||
#include "clients/openapi/schema.h"
|
||||
|
||||
using namespace molo::clients::openapi;
|
||||
using molo::clients::body::Json;
|
||||
|
||||
namespace {
|
||||
|
||||
ModelDecl user_model() {
|
||||
ModelDecl model;
|
||||
model.name = "User";
|
||||
model.description = "A user.";
|
||||
FieldDecl id;
|
||||
id.name = "id";
|
||||
id.type = "integer";
|
||||
id.required = true;
|
||||
FieldDecl name;
|
||||
name.name = "name";
|
||||
name.type = "string";
|
||||
name.required = true;
|
||||
name.min_length = 1;
|
||||
name.max_length = 80;
|
||||
FieldDecl role;
|
||||
role.name = "role";
|
||||
role.type = "string";
|
||||
role.enum_values = {"admin", "member"};
|
||||
model.fields = {id, name, role};
|
||||
return model;
|
||||
}
|
||||
|
||||
std::vector<RouteDecl> sample_routes() {
|
||||
RouteDecl list;
|
||||
list.method = "GET";
|
||||
list.path = "/v1/users";
|
||||
list.operation_id = "listUsers";
|
||||
list.summary = "List users";
|
||||
list.tags = {"users"};
|
||||
ParameterDecl page;
|
||||
page.name = "page";
|
||||
page.in = "query";
|
||||
page.schema = Json::object();
|
||||
page.schema.set("type", Json("integer"));
|
||||
list.parameters = {page};
|
||||
list.responses = {{"200", "UserList"}};
|
||||
|
||||
RouteDecl create;
|
||||
create.method = "POST";
|
||||
create.path = "/v1/users";
|
||||
create.operation_id = "createUser";
|
||||
create.request_model = "UserCreate";
|
||||
create.responses = {{"201", "User"}, {"422", ""}};
|
||||
create.security = {"bearerAuth"};
|
||||
return {list, create};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(openapi, schema_converter) {
|
||||
Json schema = SchemaConverter::convert(user_model());
|
||||
ASSERT_EQ(schema.find("type")->as_string(), "object");
|
||||
const Json* required = schema.find("required");
|
||||
ASSERT_TRUE(required && required->is_array());
|
||||
ASSERT_EQ(required->as_array().size(), 2u);
|
||||
const Json* props = schema.find("properties");
|
||||
ASSERT_TRUE(props && props->is_object());
|
||||
ASSERT_EQ(props->find("role")->find("enum")->as_array().size(), 2u);
|
||||
FieldDecl owner;
|
||||
owner.name = "owner";
|
||||
owner.ref = "User";
|
||||
ASSERT_EQ(SchemaConverter::field_schema(owner).find("$ref")->as_string(),
|
||||
"#/components/schemas/User");
|
||||
}
|
||||
|
||||
TEST(openapi, build_and_snapshot) {
|
||||
BuilderInput input;
|
||||
input.info.title = "Demo";
|
||||
input.info.version = "1.0.0";
|
||||
input.servers = {ServerDecl{"https://api.test", "prod"}};
|
||||
input.routes = sample_routes();
|
||||
input.models = {user_model()};
|
||||
SecuritySchemeDecl bearer;
|
||||
bearer.type = "http";
|
||||
bearer.scheme = "bearer";
|
||||
bearer.bearer_format = "JWT";
|
||||
input.security_schemes["bearerAuth"] = bearer;
|
||||
input.tags = {"users"};
|
||||
Builder builder;
|
||||
Document doc = builder.build(input);
|
||||
std::string json = doc.to_json_string();
|
||||
ASSERT_TRUE(json.find("\"openapi\":\"3.1.0\"") != std::string::npos);
|
||||
ASSERT_TRUE(json.find("/v1/users") != std::string::npos);
|
||||
ASSERT_TRUE(json.find("listUsers") != std::string::npos);
|
||||
ASSERT_TRUE(json.find("#/components/schemas/User") != std::string::npos);
|
||||
ASSERT_TRUE(json.find("x-molo-framework-version") != std::string::npos);
|
||||
ASSERT_TRUE(json.find("bearerAuth") != std::string::npos);
|
||||
// Undeclared descriptions render as TBD, never invented.
|
||||
ASSERT_TRUE(json.find("\"description\":\"TBD\"") != std::string::npos);
|
||||
Json parsed = Json::parse(json);
|
||||
ASSERT_TRUE(parsed.find("paths")->find("/v1/users")->has("get"));
|
||||
ASSERT_TRUE(parsed.find("paths")->find("/v1/users")->has("post"));
|
||||
}
|
||||
|
||||
TEST(openapi, deterministic_bytes) {
|
||||
Builder builder;
|
||||
auto routes = sample_routes();
|
||||
auto models = std::vector<ModelDecl>{user_model()};
|
||||
std::string first = builder.from_routes(routes, models).to_json_string();
|
||||
std::string second = builder.from_routes(routes, models).to_json_string();
|
||||
ASSERT_EQ(first, second);
|
||||
std::string yaml_first =
|
||||
builder.from_routes(routes, models).to_yaml_string();
|
||||
std::string yaml_second =
|
||||
builder.from_routes(routes, models).to_yaml_string();
|
||||
ASSERT_EQ(yaml_first, yaml_second);
|
||||
ASSERT_TRUE(yaml_first.find("openapi:") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(openapi, caps_error) {
|
||||
BuilderInput input;
|
||||
for (int i = 0; i < 5001; ++i) {
|
||||
RouteDecl route;
|
||||
route.method = "GET";
|
||||
route.path = "/r" + std::to_string(i);
|
||||
input.routes.push_back(route);
|
||||
}
|
||||
Builder builder;
|
||||
ASSERT_THROW(builder.build(input), OpenApiError);
|
||||
}
|
||||
|
||||
TEST(openapi, routes_table) {
|
||||
Builder builder;
|
||||
Document doc =
|
||||
builder.from_routes(sample_routes(), {user_model()});
|
||||
auto table = doc_route_table(doc);
|
||||
ASSERT_EQ(table.size(), 4u);
|
||||
ASSERT_TRUE(table.count("/openapi.json") == 1);
|
||||
ASSERT_TRUE(table.count("/openapi.yaml") == 1);
|
||||
ASSERT_TRUE(table.count("/docs") == 1);
|
||||
ASSERT_TRUE(table.count("/redoc") == 1);
|
||||
ASSERT_EQ(table["/openapi.json"].content_type, "application/json");
|
||||
ASSERT_TRUE(table["/openapi.json"].body.find("\"openapi\"") !=
|
||||
std::string::npos);
|
||||
ASSERT_TRUE(table["/docs"].body.find("MOLO_OPENAPI_URL") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(openapi, extend_hook_and_extensions) {
|
||||
Builder builder;
|
||||
builder.extend_hook([](Document& doc) {
|
||||
doc.extensions()["x-team"] = Json("clients");
|
||||
});
|
||||
Document doc = builder.from_routes(sample_routes(), {});
|
||||
ASSERT_TRUE(doc.to_json_string().find("x-team") != std::string::npos);
|
||||
apply_overrides(doc, nullptr);
|
||||
doc.extensions()["bad-key"] = Json(1);
|
||||
ASSERT_THROW(apply_overrides(doc, nullptr), OpenApiError);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
#include "framework.h"
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
#include "clients/proxy.h"
|
||||
|
||||
using namespace molo::clients;
|
||||
|
||||
TEST(proxy, no_proxy_match_matrix) {
|
||||
ASSERT_TRUE(no_proxy_match("*", "anything.example.com"));
|
||||
ASSERT_TRUE(no_proxy_match("example.com", "example.com"));
|
||||
ASSERT_TRUE(no_proxy_match("example.com", "a.example.com"));
|
||||
ASSERT_FALSE(no_proxy_match("example.com", "example.com.evil.com"));
|
||||
ASSERT_TRUE(no_proxy_match(".example.com", "a.example.com"));
|
||||
ASSERT_TRUE(no_proxy_match(".example.com", "example.com"));
|
||||
ASSERT_TRUE(no_proxy_match("*.example.com", "a.example.com"));
|
||||
ASSERT_FALSE(no_proxy_match("*.example.com", "example.com.evil.com"));
|
||||
ASSERT_TRUE(no_proxy_match("10.0.0.0/8", "10.1.2.3"));
|
||||
ASSERT_FALSE(no_proxy_match("10.0.0.0/8", "11.0.0.1"));
|
||||
ASSERT_TRUE(no_proxy_match("192.168.1.0/24", "192.168.1.200"));
|
||||
ASSERT_FALSE(no_proxy_match("192.168.1.0/24", "192.168.2.1"));
|
||||
ASSERT_TRUE(no_proxy_match("127.0.0.1/32", "127.0.0.1"));
|
||||
ASSERT_FALSE(no_proxy_match("not a cidr/8", "10.0.0.1"));
|
||||
ASSERT_FALSE(no_proxy_match("", "example.com"));
|
||||
}
|
||||
|
||||
TEST(proxy, ipv4_parse) {
|
||||
std::uint32_t out = 0;
|
||||
ASSERT_TRUE(parse_ipv4("127.0.0.1", out));
|
||||
ASSERT_EQ(out, 0x7F000001u);
|
||||
ASSERT_FALSE(parse_ipv4("999.1.1.1", out));
|
||||
ASSERT_FALSE(parse_ipv4("1.2.3", out));
|
||||
ASSERT_FALSE(parse_ipv4("::1", out));
|
||||
}
|
||||
|
||||
TEST(proxy, select_and_bypass) {
|
||||
ProxyConfig config;
|
||||
config.http_proxy = "http://proxy:8080";
|
||||
config.https_proxy = "http://proxy:8443";
|
||||
config.no_proxy = {"internal.test", "10.0.0.0/8"};
|
||||
ProxySelector selector(config);
|
||||
auto plain = selector.select(Url::parse("http://example.com/x"));
|
||||
ASSERT_TRUE(plain.has_value());
|
||||
ASSERT_EQ(*plain, "http://proxy:8080");
|
||||
auto secure = selector.select(Url::parse("https://example.com/x"));
|
||||
ASSERT_TRUE(secure.has_value());
|
||||
ASSERT_EQ(*secure, "http://proxy:8443");
|
||||
ASSERT_FALSE(selector.select(Url::parse("http://internal.test/x")).has_value());
|
||||
ASSERT_FALSE(selector.select(Url::parse("http://10.9.9.9/x")).has_value());
|
||||
ASSERT_TRUE(selector.is_bypassed("internal.test:8080"));
|
||||
}
|
||||
|
||||
TEST(proxy, from_env) {
|
||||
setenv("HTTP_PROXY", "http://env:8080", 1);
|
||||
setenv("NO_PROXY", "localhost, 127.0.0.1", 1);
|
||||
unsetenv("HTTPS_PROXY");
|
||||
unsetenv("https_proxy");
|
||||
ProxyConfig config = ProxyConfig::from_env();
|
||||
ASSERT_EQ(config.http_proxy, "http://env:8080");
|
||||
ASSERT_EQ(config.no_proxy.size(), 2u);
|
||||
ProxySelector selector(config);
|
||||
ASSERT_FALSE(selector.select(Url::parse("http://localhost/x")).has_value());
|
||||
auto other = selector.select(Url::parse("http://example.com/x"));
|
||||
ASSERT_TRUE(other.has_value());
|
||||
unsetenv("HTTP_PROXY");
|
||||
unsetenv("NO_PROXY");
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
#include "framework.h"
|
||||
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
|
||||
#include "clients/client.h"
|
||||
#include "clients/rest/errors.h"
|
||||
#include "clients/rest/idempotency.h"
|
||||
#include "clients/rest/paginator.h"
|
||||
#include "clients/rest/resource.h"
|
||||
#include "clients/transports/mock_transport.h"
|
||||
|
||||
using namespace molo::clients;
|
||||
using molo::clients::transports::MockTransport;
|
||||
|
||||
TEST(rest, problem_details_golden) {
|
||||
ClientResponse resp =
|
||||
rest::problem_response(422, "Validation failed", "bad age", "/v1/users");
|
||||
ASSERT_EQ(resp.status(), 422);
|
||||
ASSERT_EQ(resp.content_type(), "application/problem+json");
|
||||
body::Json parsed = resp.json();
|
||||
ASSERT_EQ(parsed.find("title")->as_string(), "Validation failed");
|
||||
ASSERT_EQ(parsed.find("detail")->as_string(), "bad age");
|
||||
ASSERT_EQ(parsed.find("status")->as_int(), 422);
|
||||
ASSERT_THROW(rest::raise_for_status(resp), rest::RestError);
|
||||
try {
|
||||
rest::raise_for_status(resp);
|
||||
} catch (const rest::RestError& err) {
|
||||
ASSERT_EQ(err.status(), 422);
|
||||
ASSERT_TRUE(std::string(err.what()).find("Validation failed") !=
|
||||
std::string::npos);
|
||||
}
|
||||
ClientResponse ok = ClientResponse(200, HeaderMap{}, "fine");
|
||||
rest::raise_for_status(ok); // Must not throw.
|
||||
}
|
||||
|
||||
TEST(rest, validation_error_shape) {
|
||||
body::Json doc = body::Json::object();
|
||||
doc.set("title", body::Json("Validation failed"));
|
||||
doc.set("status", body::Json(422));
|
||||
body::Json errors = body::Json::array();
|
||||
body::Json field = body::Json::object();
|
||||
field.set("field", body::Json("age"));
|
||||
field.set("message", body::Json("must be positive"));
|
||||
errors.push(field);
|
||||
doc.set("errors", errors);
|
||||
rest::ProblemDetails problem = rest::ProblemDetails::parse(doc);
|
||||
ASSERT_EQ(problem.errors.size(), 1u);
|
||||
ASSERT_EQ(problem.errors[0].field, "age");
|
||||
body::Json roundtrip = problem.to_json();
|
||||
ASSERT_TRUE(roundtrip.equals(doc) || roundtrip.has("errors"));
|
||||
}
|
||||
|
||||
TEST(rest, resource_crud_paths) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
raw->expect_status(Method::kGet, "/v1/users", 200, "[]");
|
||||
raw->expect_status(Method::kGet, "/v1/users/7", 200, "{}");
|
||||
raw->expect_status(Method::kPost, "/v1/users", 201, "{}");
|
||||
raw->expect_status(Method::kPut, "/v1/users/7", 200, "{}");
|
||||
raw->expect_status(Method::kPatch, "/v1/users/7", 200, "{}");
|
||||
raw->expect_status(Method::kDelete, "/v1/users/7", 204, "");
|
||||
Client client(std::move(mock));
|
||||
rest::Resource users(client, "http://h", "/v1/users");
|
||||
ASSERT_EQ(users.list_blocking().status(), 200);
|
||||
ASSERT_EQ(users.get_blocking("7").status(), 200);
|
||||
body::Json doc = body::Json::object();
|
||||
doc.set("name", body::Json("ada"));
|
||||
ASSERT_EQ(users.create_blocking(doc).status(), 201);
|
||||
ASSERT_EQ(users.update_blocking("7", doc).status(), 200);
|
||||
ASSERT_EQ(users.patch_blocking("7", doc).status(), 200);
|
||||
ASSERT_EQ(users.remove_blocking("7").status(), 204);
|
||||
raw->verify();
|
||||
auto seen = raw->seen();
|
||||
ASSERT_EQ(seen.size(), 6u);
|
||||
ASSERT_EQ(seen[0].target, "/v1/users");
|
||||
ASSERT_TRUE(seen[2].headers.has("Idempotency-Key"));
|
||||
ASSERT_TRUE(seen[2].body.find("ada") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(rest, paginator_walks_250_items) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
auto page_body = [](int page, int per_page, int total) {
|
||||
int start = (page - 1) * per_page;
|
||||
int end = start + per_page < total ? start + per_page : total;
|
||||
std::ostringstream out;
|
||||
out << "{\"data\":[";
|
||||
for (int i = start; i < end; ++i) {
|
||||
if (i > start) out << ",";
|
||||
out << "{\"id\":" << i << "}";
|
||||
}
|
||||
out << "],\"meta\":{\"page\":" << page << ",\"per_page\":" << per_page
|
||||
<< ",\"total\":" << total << "},\"links\":{}}";
|
||||
return out.str();
|
||||
};
|
||||
raw->expect_status(Method::kGet, "/v1/users", 200, page_body(1, 100, 250),
|
||||
"application/json");
|
||||
raw->expect_status(Method::kGet, "/v1/users", 200, page_body(2, 100, 250),
|
||||
"application/json");
|
||||
raw->expect_status(Method::kGet, "/v1/users", 200, page_body(3, 100, 250),
|
||||
"application/json");
|
||||
Client client(std::move(mock));
|
||||
rest::Paginator paginator(client, "http://h/v1/users");
|
||||
paginator.per_page(100);
|
||||
std::vector<body::Json> all = paginator.fetch_all_blocking();
|
||||
ASSERT_EQ(all.size(), 250u);
|
||||
ASSERT_EQ(all[0].find("id")->as_int(), 0);
|
||||
ASSERT_EQ(all[249].find("id")->as_int(), 249);
|
||||
raw->verify();
|
||||
}
|
||||
|
||||
TEST(rest, paginator_cursor_style) {
|
||||
auto mock = std::make_unique<MockTransport>();
|
||||
MockTransport* raw = mock.get();
|
||||
raw->expect_status(Method::kGet, "/v1/feed", 200,
|
||||
R"({"data":[{"id":1}],"meta":{"next_cursor":"c2"},"links":{}})",
|
||||
"application/json");
|
||||
raw->expect_status(Method::kGet, "/v1/feed", 200,
|
||||
R"({"data":[{"id":2}],"meta":{},"links":{}})",
|
||||
"application/json");
|
||||
Client client(std::move(mock));
|
||||
rest::Paginator paginator(client, "http://h/v1/feed");
|
||||
std::vector<body::Json> all = paginator.fetch_all_blocking();
|
||||
ASSERT_EQ(all.size(), 2u);
|
||||
raw->verify();
|
||||
}
|
||||
|
||||
TEST(rest, idempotency_store_replay) {
|
||||
rest::InMemoryIdempotencyStore store;
|
||||
ASSERT_TRUE(!store.lookup("k1").has_value());
|
||||
rest::IdempotentResult result;
|
||||
result.status = 201;
|
||||
result.body = "{}";
|
||||
result.content_type = "application/json";
|
||||
store.store("k1", result);
|
||||
auto replay = store.lookup("k1");
|
||||
ASSERT_TRUE(replay.has_value());
|
||||
ASSERT_EQ(replay->status, 201);
|
||||
ASSERT_EQ(store.size(), 1u);
|
||||
std::string key = rest::IdempotencyKey::generate();
|
||||
ASSERT_EQ(key.size(), 32u);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
#include "framework.h"
|
||||
|
||||
#include "clients/openapi/builder.h"
|
||||
#include "clients/openapi/schema.h"
|
||||
#include "clients/testing/assertions.h"
|
||||
#include "clients/testing/clock.h"
|
||||
#include "clients/testing/fixtures.h"
|
||||
#include "clients/testing/test_client.h"
|
||||
|
||||
using namespace molo::clients;
|
||||
using namespace molo::clients::testing;
|
||||
|
||||
namespace {
|
||||
|
||||
ClientResponse echo_app(const ClientRequest& req) {
|
||||
HeaderMap headers;
|
||||
headers.set("Content-Type", "application/json");
|
||||
headers.set("X-Echo-Path", req.url().path());
|
||||
body::Json doc = body::Json::object();
|
||||
doc.set("method", body::Json(method_name(req.method())));
|
||||
doc.set("path", body::Json(req.url().path()));
|
||||
doc.set("now", body::Json((int)Clock::now()));
|
||||
return ClientResponse(200, std::move(headers), doc.dump());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(testing, client_verbs_like_production) {
|
||||
TestClient client(echo_app);
|
||||
auto guard = client.lifespan();
|
||||
ClientResponse resp = client.get_blocking("http://app.test/v1/echo");
|
||||
testing::expect_status(resp, 200);
|
||||
testing::expect_header(resp, "X-Echo-Path", "/v1/echo");
|
||||
body::Json parsed = resp.json();
|
||||
ASSERT_EQ(parsed.find("method")->as_string(), "GET");
|
||||
ClientResponse posted =
|
||||
client.post_blocking("http://app.test/v1/echo", "{}");
|
||||
ASSERT_EQ(posted.json().find("method")->as_string(), "POST");
|
||||
ASSERT_EQ(client.dispatch_count(), 2u);
|
||||
// Zero real sockets: the pool never created a connection.
|
||||
ASSERT_EQ(client.pool().stats().created, 0u);
|
||||
}
|
||||
|
||||
TEST(testing, lifespan_hooks_fire) {
|
||||
bool started = false;
|
||||
bool stopped = false;
|
||||
TestClient client(echo_app);
|
||||
client.app_transport().on_startup([&] { started = true; });
|
||||
client.app_transport().on_shutdown([&] { stopped = true; });
|
||||
{
|
||||
auto guard = client.lifespan();
|
||||
ASSERT_TRUE(started);
|
||||
ASSERT_TRUE(client.app_transport().started());
|
||||
}
|
||||
ASSERT_TRUE(stopped);
|
||||
ASSERT_FALSE(client.app_transport().started());
|
||||
}
|
||||
|
||||
TEST(testing, fixtures_and_db) {
|
||||
FixtureRegistry registry;
|
||||
std::vector<std::string> order;
|
||||
FixtureHooks hooks;
|
||||
hooks.setup = [&] { order.push_back("setup"); };
|
||||
hooks.teardown = [&] { order.push_back("teardown"); };
|
||||
registry.define("db", hooks);
|
||||
registry.setup_all();
|
||||
InMemoryDb db;
|
||||
SeededFactory factory;
|
||||
factory.define("user", [](int seq) {
|
||||
body::Json row = body::Json::object();
|
||||
row.set("id", body::Json(seq));
|
||||
return row;
|
||||
});
|
||||
for (auto& row : factory.create_many("user", 3)) db.insert("users", row);
|
||||
ASSERT_EQ(db.count("users"), 3u);
|
||||
ASSERT_EQ(db.all("users")[2].find("id")->as_int(), 3);
|
||||
db.reset();
|
||||
ASSERT_EQ(db.count("users"), 0u);
|
||||
registry.teardown_all();
|
||||
ASSERT_EQ(order.size(), 2u);
|
||||
ASSERT_EQ(order[0], "setup");
|
||||
ASSERT_EQ(order[1], "teardown");
|
||||
ASSERT_THROW(registry.setup_one("missing"), FixtureError);
|
||||
}
|
||||
|
||||
TEST(testing, frozen_clock) {
|
||||
Clock::freeze(1700000000);
|
||||
ASSERT_TRUE(Clock::frozen());
|
||||
ASSERT_EQ(Clock::now(), 1700000000);
|
||||
TestClient client(echo_app);
|
||||
body::Json first =
|
||||
client.get_blocking("http://app.test/t").json();
|
||||
body::Json second =
|
||||
client.get_blocking("http://app.test/t").json();
|
||||
ASSERT_EQ(first.find("now")->as_int(), second.find("now")->as_int());
|
||||
Clock::advance(std::chrono::seconds(60));
|
||||
ASSERT_EQ(Clock::now(), 1700000060);
|
||||
Clock::unfreeze();
|
||||
ASSERT_FALSE(Clock::frozen());
|
||||
}
|
||||
|
||||
TEST(testing, assertion_failures) {
|
||||
ClientResponse resp = ClientResponse(200, HeaderMap{}, R"({"a":1})");
|
||||
testing::expect_status(resp, 200);
|
||||
ASSERT_THROW(testing::expect_status(resp, 404), ExpectError);
|
||||
ASSERT_THROW(testing::expect_header(resp, "X-Missing", "v"), ExpectError);
|
||||
body::Json want = body::Json::object();
|
||||
want.set("a", body::Json(2));
|
||||
ASSERT_THROW(testing::expect_json(resp, want), ExpectError);
|
||||
body::Json subset = body::Json::object();
|
||||
subset.set("a", body::Json(1));
|
||||
testing::expect_json_subset(resp.json(), subset);
|
||||
body::Json bad_subset = body::Json::object();
|
||||
bad_subset.set("b", body::Json(1));
|
||||
ASSERT_THROW(testing::expect_json_subset(resp.json(), bad_subset),
|
||||
ExpectError);
|
||||
}
|
||||
|
||||
TEST(testing, schema_conformance) {
|
||||
openapi::ModelDecl user;
|
||||
user.name = "User";
|
||||
openapi::FieldDecl id;
|
||||
id.name = "id";
|
||||
id.type = "integer";
|
||||
id.required = true;
|
||||
openapi::FieldDecl name;
|
||||
name.name = "name";
|
||||
name.type = "string";
|
||||
name.required = true;
|
||||
user.fields = {id, name};
|
||||
openapi::Builder builder;
|
||||
openapi::Document doc = builder.from_routes({}, {user});
|
||||
|
||||
body::Json good = body::Json::object();
|
||||
good.set("id", body::Json(7));
|
||||
good.set("name", body::Json("ada"));
|
||||
testing::expect_schema_by_name(good, "User", doc);
|
||||
|
||||
body::Json missing = body::Json::object();
|
||||
missing.set("id", body::Json(7));
|
||||
ASSERT_THROW(testing::expect_schema_by_name(missing, "User", doc),
|
||||
ExpectError);
|
||||
|
||||
body::Json wrong_type = body::Json::object();
|
||||
wrong_type.set("id", body::Json("seven"));
|
||||
wrong_type.set("name", body::Json("ada"));
|
||||
ASSERT_THROW(testing::expect_schema_by_name(wrong_type, "User", doc),
|
||||
ExpectError);
|
||||
ASSERT_THROW(testing::expect_schema_by_name(good, "Nope", doc), ExpectError);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
#include "framework.h"
|
||||
|
||||
#include "clients/url.h"
|
||||
|
||||
using molo::clients::Url;
|
||||
using molo::clients::UrlError;
|
||||
|
||||
TEST(url, parse_full) {
|
||||
Url url = Url::parse("https://user:pass@example.com:8443/v1/users?page=2&x=a%20b#frag");
|
||||
ASSERT_EQ(url.scheme(), "https");
|
||||
ASSERT_EQ(url.host(), "example.com");
|
||||
ASSERT_EQ(url.port(), 8443);
|
||||
ASSERT_EQ(url.path(), "/v1/users");
|
||||
ASSERT_EQ(url.fragment(), "frag");
|
||||
ASSERT_TRUE(url.is_https());
|
||||
auto page = url.query_value("page");
|
||||
ASSERT_TRUE(page.has_value());
|
||||
ASSERT_EQ(*page, "2");
|
||||
auto x = url.query_value("x");
|
||||
ASSERT_TRUE(x.has_value());
|
||||
ASSERT_EQ(*x, "a b");
|
||||
ASSERT_EQ(url.target(), "/v1/users?page=2&x=a%20b");
|
||||
ASSERT_EQ(url.host_port(), "example.com:8443");
|
||||
ASSERT_EQ(url.pool_key(), "https://example.com:8443");
|
||||
}
|
||||
|
||||
TEST(url, default_ports) {
|
||||
ASSERT_EQ(Url::parse("http://h/").port(), 80);
|
||||
ASSERT_EQ(Url::parse("https://h/").port(), 443);
|
||||
ASSERT_EQ(Url::parse("http://h/").origin(), "http://h");
|
||||
ASSERT_EQ(Url::parse("http://h:8080/").origin(), "http://h:8080");
|
||||
}
|
||||
|
||||
TEST(url, case_and_ipv6) {
|
||||
Url url = Url::parse("HTTP://EXAMPLE.COM/Path");
|
||||
ASSERT_EQ(url.scheme(), "http");
|
||||
ASSERT_EQ(url.host(), "example.com");
|
||||
Url v6 = Url::parse("http://[::1]:8080/x");
|
||||
ASSERT_EQ(v6.host(), "[::1]");
|
||||
ASSERT_EQ(v6.port(), 8080);
|
||||
}
|
||||
|
||||
TEST(url, join_matrix) {
|
||||
Url base = Url::parse("http://h:8080/a/b/c?x=1");
|
||||
ASSERT_EQ(base.join("http://other/x").str(), "http://other/x");
|
||||
ASSERT_EQ(base.join("/abs?q=2").str(), "http://h:8080/abs?q=2");
|
||||
ASSERT_EQ(base.join("rel").str(), "http://h:8080/a/b/rel");
|
||||
ASSERT_EQ(base.join("../up").str(), "http://h:8080/a/up");
|
||||
ASSERT_EQ(base.join("./dot").str(), "http://h:8080/a/b/dot");
|
||||
ASSERT_EQ(base.join("?only=query").str(), "http://h:8080/a/b/c?only=query");
|
||||
ASSERT_EQ(base.join("#frag").str(), "http://h:8080/a/b/c?x=1");
|
||||
ASSERT_EQ(base.join("").str(), "http://h:8080/a/b/c?x=1");
|
||||
}
|
||||
|
||||
TEST(url, encode_roundtrip) {
|
||||
std::string raw = "a b/c?d=e&f+g";
|
||||
std::string enc = Url::encode_component(raw);
|
||||
ASSERT_EQ(Url::decode_component(enc), raw);
|
||||
ASSERT_EQ(Url::decode_component("a+b"), "a b");
|
||||
}
|
||||
|
||||
TEST(url, query_mutation) {
|
||||
Url url = Url::parse("http://h/items");
|
||||
url.set_query_arg("page", "1");
|
||||
url.set_query_arg("per_page", "20");
|
||||
url.set_query_arg("page", "3");
|
||||
ASSERT_EQ(url.query_string(), "page=3&per_page=20");
|
||||
}
|
||||
|
||||
TEST(url, errors) {
|
||||
ASSERT_THROW(Url::parse(""), UrlError);
|
||||
ASSERT_THROW(Url::parse("http:///no-host"), UrlError);
|
||||
ASSERT_THROW(Url::decode_component("%zz"), UrlError);
|
||||
ASSERT_THROW(Url::parse(std::string(9000, 'a')), UrlError);
|
||||
}
|
||||
Reference in New Issue
Block a user