Skip to content

Commit

Permalink
feat: add get_ttl
Browse files Browse the repository at this point in the history
* cache.py: item_ttl

* cache.py: del expired item

* Update src/cacheout/cache.py

Co-authored-by: Derrick Gilland <dgilland@gmail.com>

* test_cache.py: add tests for get_ttl()

* refactor and tests

* format code

---------

Co-authored-by: Derrick Gilland <dgilland@gmail.com>
  • Loading branch information
uncle-lv and dgilland authored Jan 29, 2023
1 parent 3143da0 commit 11ba7fd
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/cacheout/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
15 changes: 15 additions & 0 deletions tests/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 11ba7fd

Please sign in to comment.