From 1bbe3a049f6fe3af809f80a2dd51c5727d69ff74 Mon Sep 17 00:00:00 2001 From: lbgracioso Date: Mon, 11 Dec 2023 09:49:19 -0300 Subject: [PATCH] Update Server::setFQDN and add unit tests Signed-off-by: lbgracioso --- include/cloysterhpc/server.h | 2 +- src/server.cpp | 48 ++++++++++++++++++++++++------------ 2 files changed, 33 insertions(+), 17 deletions(-) diff --git a/include/cloysterhpc/server.h b/include/cloysterhpc/server.h index 938f7a6d..0247f20b 100644 --- a/include/cloysterhpc/server.h +++ b/include/cloysterhpc/server.h @@ -26,7 +26,6 @@ class Server { std::string m_fqdn; // TODO: Remove? protected: - Server() = default; Server(std::string_view hostname, OS& os, CPU& cpu, std::list&& connections, std::optional bmc = std::nullopt); @@ -62,6 +61,7 @@ class Server { void setBMC(const BMC& bmc); virtual ~Server() = default; + Server() = default; }; #endif // CLOYSTERHPC_SERVER_H_ diff --git a/src/server.cpp b/src/server.cpp index 8bae4240..345d44a7 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -65,21 +65,7 @@ void Server::setFQDN(const std::string& fqdn) // This pattern validates whether an FQDN is valid or not. const std::regex fqdnPattern( - R"regex(^ - ( # Start of FQDN - ( # Start of label (subdomain) - [a-zA-Z0-9] # First character of label - [a-zA-Z0-9\\-]* # Zero or more valid characters in label - [a-zA-Z0-9] # Last character of label - ) # End of label - \. # Dot separator - )* # Zero or more labels - ( # Start of last label (TLD) - [A-Za-z0-9] # First character of label (TLD) - [A-Za-z0-9\\-]* # Zero or more valid characters in label - [A-Za-z0-9] # Last character of label (TLD) - ) # End of last label (TLD) - $)regex"); + R"regex(^(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9\\-]*[A-Za-z0-9])?$)regex"); if (!std::regex_match(fqdn, fqdnPattern)) throw std::runtime_error("Invalid FQDN format"); @@ -141,4 +127,34 @@ void Server::setBMC(const BMC& bmc) { m_bmc = bmc; } const CPU& Server::getCPU() const noexcept { return m_cpu; } -void Server::setCPU(const CPU& cpu) { m_cpu = cpu; } \ No newline at end of file +void Server::setCPU(const CPU& cpu) { m_cpu = cpu; } + + +#ifdef BUILD_TESTING +#include +#else +#define DOCTEST_CONFIG_DISABLE +#include +#endif + +TEST_SUITE("Test FQDN") +{ + TEST_CASE("FQDN Validation with Server::setFQDN") { + Server server; + + SUBCASE("Valid FQDNs") { + CHECK_NOTHROW(server.setFQDN("example.com")); + CHECK_NOTHROW(server.setFQDN("subdomain.example.com")); + CHECK_NOTHROW(server.setFQDN("sub-domain.example.co.uk")); + } + + SUBCASE("Invalid FQDNs") { + CHECK_THROWS(server.setFQDN("example")); // Missing TLD + CHECK_THROWS(server.setFQDN(".example.com")); // Leading dot + CHECK_THROWS(server.setFQDN("example.com.")); // Trailing dot + CHECK_THROWS(server.setFQDN("example..com")); // Double dot + CHECK_THROWS(server.setFQDN("example@com")); // Invalid character + CHECK_THROWS(server.setFQDN(std::string(256, 'a'))); // FQDN too long + } + } +}