#include #include #include #include #include #include namespace { using Void::Cache::Cache; using Void::Cache::Policy; using Void::Testing::Test; using namespace std::chrono_literals; using TP = std::chrono::steady_clock::time_point; // A manually-advanced clock for deterministic TTL tests. 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 CacheTests : Void::Testing::Suite { // ── TTL ─────────────────────────────────────────────────── Test ttl_expires_lazily() { ManualClock clk; Cache c{4, Policy::LRU, 100ms, clk.fn()}; c.put(1, "a"); clk.advance(50ms); Void::Testing::expect(c.get(1).has_value()); clk.advance(60ms); // now 110ms > 100ms TTL Void::Testing::expect(!c.get(1).has_value()); Void::Testing::expect_eq(c.stats().expirations, std::uint64_t{1}); } Test per_entry_ttl_overrides_default() { ManualClock clk; Cache c{4, Policy::LRU, 100ms, clk.fn()}; c.put(1, 10, 10ms); // shorter than default clk.advance(20ms); Void::Testing::expect(!c.get(1).has_value()); } Test sweep_purges_expired() { ManualClock clk; Cache c{8, Policy::LRU, 10ms, clk.fn()}; c.put(1, 1); c.put(2, 2); clk.advance(20ms); Void::Testing::expect_eq(c.sweep(), std::size_t{2}); Void::Testing::expect_eq(c.size(), std::size_t{0}); } // ── eviction policies ───────────────────────────────────── Test lru_evicts_least_recently_used() { Cache c{2, Policy::LRU}; c.put(1, 1); c.put(2, 2); (void)c.get(1); // promote 1 c.put(3, 3); // evicts 2 Void::Testing::expect(c.contains(1)); Void::Testing::expect(!c.contains(2)); Void::Testing::expect(c.contains(3)); } Test fifo_evicts_oldest_inserted() { Cache c{2, Policy::FIFO}; c.put(1, 1); c.put(2, 2); (void)c.get(1); // does NOT promote under FIFO c.put(3, 3); // evicts 1 (oldest inserted) Void::Testing::expect(!c.contains(1)); Void::Testing::expect(c.contains(2)); Void::Testing::expect(c.contains(3)); } Test lfu_evicts_least_frequently_used() { Cache c{2, Policy::LFU}; c.put(1, 1); c.put(2, 2); (void)c.get(1); (void)c.get(1); // 1 is hot c.put(3, 3); // evicts 2 (lower frequency) Void::Testing::expect(c.contains(1)); Void::Testing::expect(!c.contains(2)); Void::Testing::expect(c.contains(3)); } // ── stats ───────────────────────────────────────────────── Test stats_track_hits_and_misses() { Cache c{4}; c.put(1, 1); (void)c.get(1); // hit (void)c.get(2); // miss (void)c.get(1); // hit const auto s = c.stats(); Void::Testing::expect_eq(s.hits, std::uint64_t{2}); Void::Testing::expect_eq(s.misses, std::uint64_t{1}); } Test stats_track_evictions() { Cache c{1, Policy::LRU}; c.put(1, 1); c.put(2, 2); // evicts 1 Void::Testing::expect_eq(c.stats().evictions, std::uint64_t{1}); } }; } // namespace