#include #include #include #include #include #include #include using Void::Service::IService; using Void::Service::ServiceRegistry; namespace { // A plain interface (does not derive IService) — still resolvable. class IClock { public: virtual ~IClock() = default; [[nodiscard]] virtual int now() const = 0; }; class FixedClock final : public IClock { public: explicit FixedClock(int t) : m_t(t) {} [[nodiscard]] int now() const override { return m_t; } int m_t; }; // A lifecycle service (derives IService). class IGreeter { public: virtual ~IGreeter() = default; [[nodiscard]] virtual std::string greet() const = 0; }; class Greeter final : public IService, public IGreeter { public: explicit Greeter(std::vector* log) : m_log(log) {} [[nodiscard]] std::string_view service_name() const override { return "Greeter"; } void on_start() override { m_log->push_back("start"); } void on_stop() override { m_log->push_back("stop"); } [[nodiscard]] std::string greet() const override { return "hi"; } std::vector* m_log; }; // A plain, non-polymorphic value type registered directly as a service. struct Config { int port = 8080; std::string host = "localhost"; }; } // namespace Void::Testing::Test registry_provides_non_polymorphic_service() { ServiceRegistry reg; reg.provide(std::make_shared(Config{.port = 9000})); auto cfg = reg.get(); Void::Testing::expect(cfg != nullptr); Void::Testing::expect_eq(cfg->port, 9000); Void::Testing::expect(reg.has()); // No IService lifecycle aspect, but start_all/stop_all must not choke. reg.start_all(); reg.stop_all(); } Void::Testing::Test registry_provide_and_get() { ServiceRegistry reg; reg.provide(std::make_shared(42)); auto clock = reg.get(); Void::Testing::expect(clock != nullptr); Void::Testing::expect_eq(clock->now(), 42); } Void::Testing::Test registry_missing_get_is_null_require_throws() { ServiceRegistry reg; Void::Testing::expect(reg.get() == nullptr); Void::Testing::expect(!reg.has()); bool threw = false; try { (void)reg.require(); } catch (const std::exception&) { threw = true; } Void::Testing::expect(threw); } Void::Testing::Test registry_require_returns_reference() { ServiceRegistry reg; reg.provide(std::make_shared(7)); Void::Testing::expect_eq(reg.require().now(), 7); Void::Testing::expect(reg.has()); } Void::Testing::Test registry_replace_provider() { ServiceRegistry reg; reg.provide(std::make_shared(1)); reg.provide(std::make_shared(2)); Void::Testing::expect_eq(reg.require().now(), 2); Void::Testing::expect_eq(reg.size(), std::size_t{1}); } Void::Testing::Test registry_lifecycle_order() { std::vector log; ServiceRegistry reg; reg.provide(std::make_shared(&log)); reg.start_all(); reg.stop_all(); Void::Testing::expect_eq(log.size(), std::size_t{2}); Void::Testing::expect_eq(log[0], std::string{"start"}); Void::Testing::expect_eq(log[1], std::string{"stop"}); // Resolvable through the IGreeter interface. Void::Testing::expect_eq(reg.require().greet(), std::string{"hi"}); }