#include #include #include #include #include namespace { using Void::Resilience::TokenBucket; using Void::Testing::Test; 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 RateLimiterTests : Void::Testing::Suite { Test starts_full_and_drains() { ManualClock clk; TokenBucket b{10.0, 5.0, clk.fn()}; Void::Testing::expect(b.try_acquire(10.0)); // drains the bucket Void::Testing::expect(!b.try_acquire(1.0)); // now empty } Test refills_over_time() { ManualClock clk; TokenBucket b{10.0, 5.0, clk.fn()}; Void::Testing::expect(b.try_acquire(10.0)); clk.advance(1s); // +5 tokens Void::Testing::expect(b.try_acquire(5.0)); Void::Testing::expect(!b.try_acquire(0.5)); } Test refill_is_clamped_to_capacity() { ManualClock clk; TokenBucket b{10.0, 5.0, clk.fn()}; Void::Testing::expect(b.try_acquire(10.0)); clk.advance(100s); // would be 500 tokens, clamps to 10 Void::Testing::expect(b.available() <= 10.0); Void::Testing::expect(b.available() >= 9.99); } }; } // namespace