From 11ba7fdb6bce909bc2bcbfa50cfc172463199d6d Mon Sep 17 00:00:00 2001 From: uncle-lv <88037946+uncle-lv@users.noreply.github.com> Date: Mon, 30 Jan 2023 01:05:26 +0800 Subject: [PATCH] feat: add get_ttl * cache.py: item_ttl * cache.py: del expired item * Update src/cacheout/cache.py Co-authored-by: Derrick Gilland * test_cache.py: add tests for get_ttl() * refactor and tests * format code --------- Co-authored-by: Derrick Gilland --- src/cacheout/cache.py | 21 +++++++++++++++++++++ tests/test_cache.py | 15 +++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/cacheout/cache.py b/src/cacheout/cache.py index 24b11c6..4a71326 100644 --- a/src/cacheout/cache.py +++ b/src/cacheout/cache.py @@ -443,6 +443,27 @@ def expire_times(self) -> t.Dict[t.Hashable, T_TTL]: with self._lock: return self._expire_times.copy() + def get_ttl(self, key: t.Hashable) -> t.Optional[T_TTL]: + """ + Return the remaining time to live of a key that has a TTL. + + Args: + key: Cache key. + + Returns: + The remaining time to live of `key` or ``None`` if the key doesn't exist or has expired. + """ + with self._lock: + if not self._has(key): + return None + + expire_time = self._expire_times.copy().get(key) + if expire_time is None: + return None + + ttl = expire_time - self.timer() + return ttl + def evict(self) -> int: """ Perform cache eviction per the cache replacement policy: diff --git a/tests/test_cache.py b/tests/test_cache.py index fbe07c4..b2b3ec4 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -327,6 +327,21 @@ def test_cache_delete_expired(cache: Cache, timer: Timer): assert cache.has(key) +def test_cache_get_ttl(cache: Cache, timer: Timer): + """Test that cache.get_ttl() will return the remaining time to live of a key that has a TTL.""" + cache.set("a", 1, ttl=1) + cache.set("b", 2, ttl=2) + cache.set("c", 3) + + assert cache.get_ttl("a") == 1 + + timer.time = 1 + + assert cache.get_ttl("a") is None + assert cache.get_ttl("b") == 1 + assert cache.get_ttl("c") is None + + def test_cache_evict(cache: Cache): """Test that cache.evict() will remove cache keys to make room.""" maxsize = 5