#include #include #include #include #include #include namespace { using Void::Resilience::CircuitBreaker; using Void::Testing::Test; using State = CircuitBreaker::State; using namespace std::chrono_literals; using TP = std::chrono::steady_clock::time_point; struct ManualClock { std::shared_ptr now = std::make_shared(std::chrono::steady_clock::now()); auto fn() const { auto p = now; return [p] { return *p; }; } void advance(std::chrono::nanoseconds d) const { *now += d; } }; struct CircuitBreakerTests : Void::Testing::Suite { Test trips_open_after_threshold_failures() { ManualClock clk; CircuitBreaker cb{3, 1s, 1, clk.fn()}; cb.record_failure(); cb.record_failure(); Void::Testing::expect(cb.state() == State::Closed); cb.record_failure(); // third -> open Void::Testing::expect(cb.state() == State::Open); Void::Testing::expect(!cb.allow()); } Test half_opens_after_cooldown_then_closes() { ManualClock clk; CircuitBreaker cb{2, 1s, 1, clk.fn()}; cb.record_failure(); cb.record_failure(); // open Void::Testing::expect(!cb.allow()); clk.advance(1s); Void::Testing::expect(cb.allow()); // probe admitted (half-open) Void::Testing::expect(cb.state() == State::HalfOpen); cb.record_success(); // closes Void::Testing::expect(cb.state() == State::Closed); } Test half_open_failure_reopens() { ManualClock clk; CircuitBreaker cb{2, 1s, 1, clk.fn()}; cb.record_failure(); cb.record_failure(); clk.advance(1s); (void)cb.allow(); // -> half-open cb.record_failure(); Void::Testing::expect(cb.state() == State::Open); } Test execute_gates_and_records() { ManualClock clk; CircuitBreaker cb{2, 1s, 1, clk.fn()}; const auto ok = [] { return std::expected{42}; }; const auto bad = [] { return std::expected{std::unexpect, -1}; }; auto r = cb.execute(ok); Void::Testing::expect(r.has_value()); Void::Testing::expect(r->has_value()); Void::Testing::expect_eq(r->value(), 42); (void)cb.execute(bad); (void)cb.execute(bad); // open now Void::Testing::expect(cb.state() == State::Open); auto rejected = cb.execute(ok); Void::Testing::expect(!rejected.has_value()); // circuit refused } }; } // namespace