Add echo test for server

This commit is contained in:
2025-09-14 12:56:22 -04:00
parent bd06798fd3
commit cf0c1b7cc2
2 changed files with 66 additions and 0 deletions

View File

@@ -188,6 +188,11 @@ add_executable(test_arena tests/test_arena.cpp)
target_link_libraries(test_arena doctest_impl weaseldb_sources_debug) target_link_libraries(test_arena doctest_impl weaseldb_sources_debug)
target_compile_options(test_arena PRIVATE -UNDEBUG) target_compile_options(test_arena PRIVATE -UNDEBUG)
add_executable(test_server tests/test_server.cpp)
target_link_libraries(test_server doctest_impl weaseldb_sources_debug)
target_compile_options(test_server PRIVATE -UNDEBUG)
add_test(NAME test_server COMMAND test_server)
add_executable( add_executable(
test_commit_request test_commit_request
tests/test_commit_request.cpp tests/nlohmann_reference_parser.cpp tests/test_commit_request.cpp tests/nlohmann_reference_parser.cpp

61
tests/test_server.cpp Normal file
View File

@@ -0,0 +1,61 @@
#include "config.hpp"
#include "connection.hpp"
#include "connection_handler.hpp"
#include "server.hpp"
#include <doctest/doctest.h>
#include <future>
#include <string_view>
#include <thread>
// Helper to copy a string into arena memory
static std::string_view arena_copy_string(std::string_view str, Arena &arena) {
if (str.empty()) {
return std::string_view{};
}
char *copied = arena.allocate<char>(str.size());
std::memcpy(copied, str.data(), str.size());
return std::string_view(copied, str.size());
}
struct EchoHandler : ConnectionHandler {
std::future<void> f;
void on_data_arrived(std::string_view data, Connection &conn) override {
Arena arena;
auto reply = std::span{arena.allocate<std::string_view>(1), 1};
reply[0] = arena_copy_string(data, arena);
f = std::async(std::launch::async, [wconn = conn.get_weak_ref(), reply,
arena = std::move(arena)]() mutable {
if (auto conn = wconn.lock()) {
conn->append_message(reply, std::move(arena));
} else {
REQUIRE(false);
}
});
}
};
TEST_CASE("Echo test") {
EchoHandler handler;
weaseldb::Config config;
config.server.io_threads = 1;
auto server = Server::create(config, handler, {});
int fd = server->create_local_connection();
auto runThread = std::thread{[&]() { server->run(); }};
SUBCASE("writes hello back") {
int w = write(fd, "hello", 5);
REQUIRE(w == 5);
char buf[6];
buf[5] = 0;
int r = read(fd, buf, 5);
REQUIRE(r == 5);
CHECK(std::string(buf) == "hello");
}
close(fd);
server->shutdown();
runThread.join();
}